testInventory.py 159 KB
Newer Older
Guillaume Michon's avatar
Guillaume Michon 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) 2004, 2005 Nexedi SARL and Contributors. All Rights Reserved.
#          Guillaume Michon <guillaume.michon@e-asc.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 30 31 32 33 34 35 36 37 38 39 40
# XXX test 1 :
#   - stepTestGetInventoryWithSelectionReport is not launched yet,
#       since it tests a behavior which does not exist yet
# XXX test 2 :
#   - There is an issue about inventory in inventory module :
#       if a movement which is older than the inventory is modified by quantity,
#       the inventory (and the following ones) must be automatically reindexed
#       (and sorted by date). It is not the case now
#   - If an aggregated item is modified by quantity, the same problem appears, but
#       should the inventory be updated by a later quantity modification on an
#       aggregated item ?

Guillaume Michon's avatar
Guillaume Michon committed
41

42
import unittest
43

44 45
from Products.ERP5Type.Utils import cartesianProduct
from copy import copy
Guillaume Michon's avatar
Guillaume Michon committed
46 47 48 49 50


from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from DateTime import DateTime
from zLOG import LOG
51
from Products.ERP5Type.tests.Sequence import SequenceList
Guillaume Michon's avatar
Guillaume Michon committed
52
from Products.ERP5Type.DateUtils import addToDate
Julien Muchembled's avatar
Julien Muchembled committed
53
from Products.ERP5.tests.testOrder import TestOrderMixin
Yusei Tahara's avatar
Yusei Tahara committed
54
from Products.ERP5Type.tests.backportUnittest import expectedFailure
55
from Products.ERP5Form.Selection import DomainSelection
56 57
from Products.ERP5Type.tests.utils import createZODBPythonScript
from textwrap import dedent
Guillaume Michon's avatar
Guillaume Michon committed
58

Jérome Perrin's avatar
Jérome Perrin committed
59
class TestInventory(TestOrderMixin, ERP5TypeTestCase):
Guillaume Michon's avatar
Guillaume Michon committed
60
  """
Jérome Perrin's avatar
Jérome Perrin committed
61
    Test Inventory API
Guillaume Michon's avatar
Guillaume Michon committed
62 63 64 65
  """
  run_all_test = 1
  packing_list_portal_type = 'Sale Packing List'
  packing_list_line_portal_type = packing_list_portal_type + ' Line'
66 67 68 69
  item_portal_type = "Apparel Fabric Item"
  inventory_portal_type = "Inventory"
  inventory_line_portal_type = inventory_portal_type + ' Line'
  inventory_cell_portal_type = inventory_portal_type + ' Cell'
70
  price_currency =  'currency_module/euro'
71

Guillaume Michon's avatar
Guillaume Michon committed
72 73 74
  def getTitle(self):
    return "Inventory"

75 76 77
  def getBusinessTemplateList(self):
    """Business Templates required for this test.
    """
78
    return ('erp5_base', 'erp5_pdm', 'erp5_simulation', 'erp5_trade',
79
            'erp5_configurator_standard_trade_template',
80
            'erp5_apparel', 'erp5_simulation_test')
81

Fabien Morin's avatar
Fabien Morin committed
82 83 84 85 86 87 88 89 90 91
  def setUpPreferences(self):
    #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')
      if preference.getPreferenceState() == 'disabled':
        preference.enable()
92

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

100 101 102 103
  def afterSetUp(self, quiet=1, run=run_all_test):
    self.login()
    self.category_tool = self.getCategoryTool()
    self.createCategories()
Jérome Perrin's avatar
Jérome Perrin committed
104
    self.validateRules()
105
    # Patch PackingList.asPacked so that we do not need
Jérome Perrin's avatar
Jérome Perrin committed
106
    # to manage containers here, this not the job of this test
107 108 109 110
    def isPacked(self):
      return 1
    from Products.ERP5Type.Document.PackingList import PackingList
    PackingList.isPacked = isPacked
111
    self.createCurrency()
112
    self.setUpPreferences()
113

114 115 116 117 118 119 120 121 122 123 124
  def beforeTearDown(self):
    """Clear everything for next test."""
    for module in [ 'portal_simulation',
                    'inventory_module']:
      folder = self.portal[module]
      folder.manage_delObjects(list(folder.objectIds()))
    self.portal.portal_skins.custom.manage_delObjects(
      list(self.portal.portal_skins.custom.objectIds()))

    self.tic()

Guillaume Michon's avatar
Guillaume Michon committed
125 126 127 128
  def createCategory(self, parent, id_list):
      last_category = None
      for category_id in id_list:
        if type(category_id) == type('a'):
Jérome Perrin's avatar
Jérome Perrin committed
129 130
          last_category = parent.newContent(portal_type='Category',
                                            id=category_id)
Guillaume Michon's avatar
Guillaume Michon committed
131 132
        else:
          self.createCategory(last_category, category_id)
133

134 135 136 137 138 139 140 141 142 143 144 145
  def stepCreateItemList(self, sequence=None, sequence_list=None, **kw):
    """
      Create some items to manipulate during the module test
    """
    item_list = []
    portal = self.getPortal()
    item_module = portal.getDefaultModule(portal_type=self.item_portal_type)
    for i in range(5):
      item = item_module.newContent(portal_type=self.item_portal_type)
      item_list.append(item)
      item.edit(quantity = (i+1)*10)
    sequence.edit(item_list = item_list)
146

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  def stepCreateOrganisationsForModule(self, sequence=None,
                                        sequence_list=None, **kw):
    """
      Create sections and nodes.
    """
    self.stepCreateOrganisation(sequence=sequence,
                        sequence_list=sequence_list, **kw)
    node = sequence.get('organisation')
    self.stepCreateOrganisation(sequence=sequence,
                        sequence_list=sequence_list, **kw)
    mirror_node = sequence.get('organisation')
    self.stepCreateOrganisation(sequence=sequence,
                        sequence_list=sequence_list, **kw)
    section = sequence.get('organisation')
    self.stepCreateOrganisation(sequence=sequence,
                        sequence_list=sequence_list, **kw)
    mirror_section = sequence.get('organisation')
164 165 166
    self.stepCreateOrganisation(sequence=sequence,
                        sequence_list=sequence_list, **kw)
    other_section = sequence.get('organisation')
167 168 169
    self.stepCreateOrganisation(sequence=sequence,
                        sequence_list=sequence_list, **kw)
    other_node = sequence.get('organisation')
170 171 172 173 174
    sequence.edit(
          node = node,
          section = section,
          mirror_node = mirror_node,
          mirror_section = mirror_section,
175
          other_section = other_section,
176
          other_node = other_node,
177 178
        )

179 180 181 182 183 184 185 186 187
  def stepCreateAggregatingInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Create a Inventory object, with a line which aggregates Items
    """
    inventory_list = sequence.get('inventory_list')
    if inventory_list is None:
      inventory_list = []
    portal = self.getPortal()
    node = sequence.get('node')
188
    section = sequence.get('section')
189 190 191 192 193
    item_list = sequence.get('item_list')
    resource = sequence.get('resource')
    inventory_module = portal.getDefaultModule(portal_type = self.inventory_portal_type)
    inventory = inventory_module.newContent(portal_type = self.inventory_portal_type)
    inventory.edit(destination_value = node,
194
                   destination_section_value = section,
195 196 197 198 199 200
                   start_date = DateTime(),
                  )
    aggregate_value_list = [item_list[0], item_list[2]]
    inventory_line = inventory.newContent(portal_type = self.inventory_line_portal_type)
    inventory_line.edit(resource_value = resource,
                        aggregate_value_list = aggregate_value_list)
201
    # Now, quantity is not defined any more automatically.
202 203
    inventory_line.edit(quantity=sum([x.getQuantity() for x in \
        aggregate_value_list]))
204
    inventory.deliver()
205 206
    inventory_list.append(inventory)
    sequence.edit(inventory_list = inventory_list)
207

208
  def createInventory(self, sequence=None, full=False, **kw):
209 210 211
    """
    """
    portal = self.getPortal()
212 213 214 215
    if kw.get('start_date', None) is not None:
      start_date = kw['start_date']
    else:
      start_date = DateTime() + 1
216
    inventory_list = sequence.get('inventory_list',[])
217 218 219
    inventory_module = portal.getDefaultModule(portal_type = self.inventory_portal_type)
    inventory = inventory_module.newContent(portal_type = self.inventory_portal_type)
    inventory.edit(destination_value = sequence.get('node'),
220
                   destination_section_value = sequence.get('section'),
221
                   start_date = start_date,
222
                   full_inventory=full,
223
                  )
224 225 226
    inventory_list.append(inventory)
    sequence.edit(inventory_list=inventory_list)
    return inventory
227

228 229 230 231 232 233
  def stepCreateSingleInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Create a single Inventory object for Inventory Module testing
    """
    inventory = self.createInventory(sequence=sequence)
    inventory_list = sequence.get('inventory_list',[])
234 235 236 237
    inventory_line = inventory.newContent(portal_type = self.inventory_line_portal_type)
    inventory_line.edit(resource_value = sequence.get('resource'),
                        inventory = 24.
                       )
238
    inventory.deliver()
239 240
    inventory_list.append(inventory)
    sequence.edit(inventory_list=inventory_list)
241

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  def stepCreateFullInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Create a full Inventory object for Inventory Module testing
    """
    inventory = self.createInventory(sequence=sequence)
    inventory_list = sequence.get('inventory_list',[])
    inventory.edit(full_inventory=True)
    inventory_line = inventory.newContent(
      portal_type = self.inventory_line_portal_type,
      resource_value = sequence.get("second_resource"),
      inventory = 101)
    inventory.deliver()
    inventory_list.append(inventory)
    sequence.edit(inventory_list=inventory_list)

  def stepCreatePartialInventoryMultipleResource(self, sequence=None, sequence_list=None, **kw):
    """
      Create a partial inventory object for one resource
    """
    inventory = self.createInventory(sequence=sequence)
    inventory_list = sequence.get('inventory_list',[])
    inventory.edit(full_inventory=False)
    inventory_line = inventory.newContent(
      portal_type = self.inventory_line_portal_type,
      resource_value = sequence.get("second_resource"),
      inventory = 101)
    inventory.deliver()
    inventory_list.append(inventory)
    sequence.edit(inventory_list=inventory_list)

  def stepTestPartialInventoryMultipleResource(self, sequence=None, sequence_list=None, **kw):
    """
      Test partial inventory behavior with multiple resource
    """
    inventory_list = sequence.get('inventory_list')
    simulation = self.getPortal().portal_simulation

    # First resource, must not have changed
    inventory = simulation.getCurrentInventory(
      resource = sequence.get("resource").getRelativeUrl(),
      section = sequence.get('section').getRelativeUrl(),
      node = sequence.get('node').getRelativeUrl(),
      )
    self.assertEquals(inventory, 100.,
                    'section=%s, node=%s' % (
                    sequence.get('section').getRelativeUrl(),
                    sequence.get('node').getRelativeUrl()))
    # second resource, must be 101
    inventory = simulation.getCurrentInventory(
      resource = sequence.get("second_resource").getRelativeUrl(),
      section = sequence.get('section').getRelativeUrl(),
      node = sequence.get('node').getRelativeUrl(),
      )
    self.assertEquals(inventory, 101.,
                    'section=%s, node=%s' % (
                    sequence.get('section').getRelativeUrl(),
                    sequence.get('node').getRelativeUrl()))



302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
  def stepCreateSingleVariatedInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Create a single Inventory object for Inventory Module testing
    """
    inventory = self.createInventory(sequence=sequence)
    inventory_line = inventory.newContent(portal_type = self.inventory_line_portal_type)
    category_list = sequence.get('variation_1')
    inventory_line.edit(resource_value = sequence.get('resource'),
                        variation_category_list=category_list
                       )
    cell = inventory_line.newCell(base_id='movement',*category_list)
    quantity=5
    cell.edit(
        quantity = quantity,
        predicate_category_list = category_list,
        variation_category_list = category_list,
        mapped_value_property_list = ['quantity'],
        )
320 321 322 323 324 325 326 327 328 329
    # When checking the not full inventory function, quantity must remain the same if
    # no inventory line defined for a variation
    inventory.deliver()


  def stepCreateFullVariatedInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Create a single full Inventory object for Inventory Module testing
    """
    inventory = self.createInventory(sequence=sequence, full=True)
330
    inventory_line = inventory.newContent(portal_type = self.inventory_line_portal_type)
331
    category_list = sequence.get('variation_1')
332 333 334 335 336
    inventory_line.edit(resource_value = sequence.get('resource'),
                        variation_category_list=category_list
                       )
    cell = inventory_line.newCell(base_id='movement',*category_list)
    cell.edit(
337
        quantity = 55,
338 339 340 341
        predicate_category_list = category_list,
        variation_category_list = category_list,
        mapped_value_property_list = ['quantity'],
        )
342 343 344 345
    inventory_line = inventory.newContent(
      portal_type = self.inventory_line_portal_type,
      resource_value = sequence.get("second_resource"),
      inventory = 101)
346
    inventory.deliver()
347

348 349
  def stepCreatePackingListForModule(self, sequence=None,
                                      sequence_list=None, **kw):
350 351 352 353
    """
      Create a single packing_list for Inventory Module testing
    """
    node = sequence.get('node')
354 355 356
    section = sequence.get('section')
    mirror_node = sequence.get('mirror_node')
    mirror_section = sequence.get('mirror_section')
357
    resource = sequence.get('resource')
358 359 360 361
    packing_list_module = self.getPortal().getDefaultModule(
                              portal_type=self.packing_list_portal_type)
    packing_list = packing_list_module.newContent(
                              portal_type=self.packing_list_portal_type)
362 363 364 365
    if kw.get('start_date', None) is not None:
      start_date = stop_date = kw['start_date']
    else:
      start_date = stop_date = DateTime() - 2
366
    packing_list.edit(
Julien Muchembled's avatar
Julien Muchembled committed
367
                      specialise=self.business_process,
368 369 370
                      source_section_value = mirror_section,
                      source_value = mirror_node,
                      destination_section_value = section,
371
                      destination_value = node,
372 373
                      start_date = start_date,
                      stop_date = stop_date,
374
                      price_currency = self.price_currency
375
                     )
376 377 378 379
    self.assertNotEquals( packing_list.getSourceSectionValue(), None)
    self.assertNotEquals( packing_list.getSourceValue(), None)
    self.assertNotEquals( packing_list.getSourceSectionValue(),
                          packing_list.getDestinationSectionValue() )
380
    sequence.edit(packing_list=packing_list)
381

382 383 384 385 386 387
  def stepCreatePackingListLine(self, sequence=None,
                                      sequence_list=None, **kw):
    """
    Create a line not variated
    """
    packing_list = sequence.get('packing_list')
388 389 390 391
    if kw.get('resource_value', None) is not None:
      resource_value = kw['resource_value']
    else:
      resource_value = sequence.get('resource')
392 393
    packing_list_line = packing_list.newContent(
                  portal_type=self.packing_list_line_portal_type)
394
    packing_list_line.edit(resource_value = resource_value,
395 396
                           quantity = 100.
                          )
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

  def stepCreateVariatedPackingListLine(self, sequence=None,
                                      sequence_list=None, **kw):
    """
    Create a line not variated
    """
    packing_list = sequence.get('packing_list')
    delivery_line_list = sequence.get('delivery_line_list',[])
    # Create Packing List Line
    packing_list_line = packing_list.newContent(portal_type=self.packing_list_line_portal_type)
    delivery_line_list.append(packing_list_line)
    resource = sequence.get('resource')
    variation_category_list = ['size/Child/32',
                               'size/Child/34',
                               'colour/%s/1' % resource.getRelativeUrl(),
                               'morphology/%s/4' % resource.getRelativeUrl()]
    packing_list_line.edit(
        resource_value = resource,
        variation_category_list=variation_category_list)
    # Set cell range

    cell_range = packing_list_line.getCellRange(base_id='movement')
    cartesian_product = cartesianProduct(cell_range)
    for cell_key in cartesian_product:
      cell = packing_list_line.newCell(base_id='movement', *cell_key)
      if 'size/Child/32' in cell_key:
        quantity = 1
        sequence.edit(variation_1=cell_key)
      elif 'size/Child/34' in cell_key:
        sequence.edit(variation_2=cell_key)
        quantity = 3
      cell.edit(
          quantity = quantity,
          predicate_category_list = cell_key,
          variation_category_list = cell_key,
          mapped_value_property_list = ['quantity'],
          )
    sequence.edit(delivery_line_list=delivery_line_list)

436 437 438 439 440 441 442 443 444
  def stepCreateVariatedNonDefaultQuantityUnitPackingListLine(
    self, sequence=None, sequence_list=None, **kw):
    """
    Create a line not variated
    """
    self.stepCreateVariatedPackingListLine(sequence, sequence_list, **kw)
    delivery_line = sequence.get('delivery_line_list')[-1]
    delivery_line.setQuantityUnitValue(self.portal.portal_categories.quantity_unit.unit.drum)

445 446
  def stepDeliverPackingList(self, sequence=None,
                                      sequence_list=None, **kw):
447
    # Switch to "started" state
448
    packing_list = sequence.get('packing_list')
449
    workflow_tool = self.getPortal().portal_workflow
450
    workflow_tool.doActionFor(packing_list,
451
                      "confirm_action", "packing_list_workflow")
452
    self.commit()
453 454 455 456
    # Apply tic so that the packing list is not in building state
    self.tic() # acceptable here because this is not the job
               # of the test to check if can do all transition
               # without processing messages
457
    workflow_tool.doActionFor(packing_list,
458
                      "set_ready_action", "packing_list_workflow")
459 460
    self.tic()
    workflow_tool.doActionFor(packing_list,
461
                      "start_action", "packing_list_workflow")
462 463 464 465
    workflow_tool.doActionFor(packing_list,
                      "stop_action", "packing_list_workflow")
    workflow_tool.doActionFor(packing_list,
                      "deliver_action", "packing_list_workflow")
466

Guillaume Michon's avatar
Guillaume Michon committed
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
  def stepCreateOrganisationList(self, sequence=None, sequence_list=None, **kw):
    """
      Create some organisations to manipulate during the test
      Organisations organigram :
        section 0 :
          - payment 1
          - nodes 2, 3
        section 4 (provider) :
          - payment 5
          - node 6
        section 7 (customer) :
          - payment  8
          - node 9
    """
    organisation_list = []
    for i in range(10):
      self.stepCreateOrganisation(sequence=sequence, sequence_list=sequence_list, **kw)
      organisation_list.append(sequence.get('organisation'))
485

Guillaume Michon's avatar
Guillaume Michon committed
486 487 488 489 490 491 492
    category_tool = self.getPortal().portal_categories
    bc = category_tool.site
    self.createCategory(bc, ['Place1', ['A', 'B'], 'Place2', ['C'], 'Place3', ['D']])
    organisation_list[2] = bc.Place1.A
    organisation_list[3] = bc.Place1.B
    organisation_list[6] = bc.Place2.C
    organisation_list[9] = bc.Place3.D
493

Guillaume Michon's avatar
Guillaume Michon committed
494 495 496
    sequence.edit(
      organisation = None,
      organisation_list = organisation_list)
497

Guillaume Michon's avatar
Guillaume Michon committed
498 499 500 501 502 503 504 505 506 507 508 509

  def stepCreateVariatedResourceList(self, sequence=None, sequence_list=None, **kw):
    """
      Create some variated resources to manipulate during the test
    """
    resource_list = []
    for i in range(3):
      self.stepCreateVariatedResource(sequence=sequence, sequence_list=sequence_list, **kw)
      resource_list.append(sequence.get('resource'))
    sequence.edit(
      resource=None,
      resource_list = resource_list)
510 511


Guillaume Michon's avatar
Guillaume Michon committed
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
  def stepCreatePackingListList(self, sequence=None, sequence_list=None, **kw):
    """
      Create some packing lists
    """
    base_category_list = ['size', 'colour', 'morphology']
    data_list = [
      { 'source':6, 'destination':2, 'source_section':4, 'destination_section':0,
        'source_payment':5, 'destination_payment':1, 'start_date':DateTime()-30, 'lines':[
           {'resource':0, 'cells': [
                             #size, colour, morphology
               {'variation':['size/Baby', '1', '4'], 'quantity':.5},
               {'variation':['size/Baby', '2', '4'], 'quantity':1.},
               {'variation':['size/Baby', '3', '4'], 'quantity':1.5},
               {'variation':['size/Baby', '1', '5'], 'quantity':2.},
               {'variation':['size/Baby', '2', '5'], 'quantity':2.5},
               {'variation':['size/Baby', '3', '5'], 'quantity':3.},

               {'variation':['size/Child/32', '1', '4'], 'quantity':3.5},
               {'variation':['size/Child/32', '2', '4'], 'quantity':4.},
               {'variation':['size/Child/32', '3', '4'], 'quantity':4.5},
               {'variation':['size/Child/32', '1', '5'], 'quantity':5.},
               {'variation':['size/Child/32', '2', '5'], 'quantity':5.5},
               {'variation':['size/Child/32', '3', '5'], 'quantity':6.},

               {'variation':['size/Child/34', '1', '4'], 'quantity':6.5},
               {'variation':['size/Child/34', '2', '4'], 'quantity':7.},
               {'variation':['size/Child/34', '3', '4'], 'quantity':7.5},
               {'variation':['size/Child/34', '1', '5'], 'quantity':8.},
               {'variation':['size/Child/34', '2', '5'], 'quantity':8.5},
               {'variation':['size/Child/34', '3', '5'], 'quantity':9.},

               {'variation':['size/Man', '1', '4'], 'quantity':9.5},
               {'variation':['size/Man', '2', '4'], 'quantity':10.},
               {'variation':['size/Man', '3', '4'], 'quantity':10.5},
               {'variation':['size/Man', '1', '5'], 'quantity':11.},
               {'variation':['size/Man', '2', '5'], 'quantity':11.5},
               {'variation':['size/Man', '3', '5'], 'quantity':12.},

               {'variation':['size/Woman', '1', '4'], 'quantity':12.5},
               {'variation':['size/Woman', '2', '4'], 'quantity':13.},
               {'variation':['size/Woman', '3', '4'], 'quantity':13.5},
               {'variation':['size/Woman', '1', '5'], 'quantity':14.},
               {'variation':['size/Woman', '2', '5'], 'quantity':14.5},
               {'variation':['size/Woman', '3', '5'], 'quantity':15.},
             ]
           }, # line end
           {'resource':1, 'cells': [
               {'variation':['size/Man', '2', '4'], 'quantity':15.5},
               {'variation':['size/Man', '3', '4'], 'quantity':16.},
             ]
           }, # line end
           {'resource':2, 'cells': [
               {'variation':['size/Baby', '3', '5'], 'quantity':16.5},
             ]
           }  # line end
567
        ]
Guillaume Michon's avatar
Guillaume Michon committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 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 622 623 624 625 626 627 628
      }, # packing list end
      { 'source':6, 'destination':3, 'source_section':4, 'destination_section':0,
        'source_payment':5, 'destination_payment':1, 'start_date':DateTime()-25, 'lines':[
           {'resource':0, 'cells': [
               {'variation':['size/Baby', '1', '4'], 'quantity':16.5},
               {'variation':['size/Baby', '2', '4'], 'quantity':17.},
               {'variation':['size/Baby', '3', '4'], 'quantity':17.5},
               {'variation':['size/Baby', '1', '5'], 'quantity':18.},
               {'variation':['size/Baby', '2', '5'], 'quantity':18.5},
               {'variation':['size/Baby', '3', '5'], 'quantity':19.},
               {'variation':['size/Woman', '2', '4'], 'quantity':19.5},
             ]
           }, # line end
           {'resource':2, 'cells': [
               {'variation':['size/Baby', '3', '5'], 'quantity':20.},
             ]
           } # line end
        ]
      }, # packing list end
      { 'source':2, 'destination':9, 'source_section':0, 'destination_section':7,
        'source_payment':1, 'destination_payment':8, 'start_date':DateTime()-15, 'lines':[
           {'resource':0, 'cells': [
               {'variation':['size/Baby', '2', '4'], 'quantity':.25},
               {'variation':['size/Baby', '3', '4'], 'quantity':.5},
               {'variation':['size/Baby', '1', '5'], 'quantity':.75},
               {'variation':['size/Baby', '2', '5'], 'quantity':1.},
               {'variation':['size/Baby', '3', '5'], 'quantity':1.25},

               {'variation':['size/Child/32', '1', '4'], 'quantity':1.5},
               {'variation':['size/Child/32', '2', '4'], 'quantity':1.75},
               {'variation':['size/Child/32', '3', '4'], 'quantity':2.},
               {'variation':['size/Child/32', '1', '5'], 'quantity':2.25},
               {'variation':['size/Child/32', '2', '5'], 'quantity':2.5},
               {'variation':['size/Child/32', '3', '5'], 'quantity':2.75},

               {'variation':['size/Child/34', '1', '4'], 'quantity':3.},
               {'variation':['size/Child/34', '2', '4'], 'quantity':3.25},
               {'variation':['size/Child/34', '3', '4'], 'quantity':3.5},
               {'variation':['size/Child/34', '1', '5'], 'quantity':3.75},
               {'variation':['size/Child/34', '2', '5'], 'quantity':4.},
               {'variation':['size/Child/34', '3', '5'], 'quantity':4.25},

               {'variation':['size/Man', '1', '4'], 'quantity':4.5},
               {'variation':['size/Man', '2', '4'], 'quantity':4.75},
               {'variation':['size/Man', '3', '4'], 'quantity':5.},
               {'variation':['size/Man', '1', '5'], 'quantity':5.25},
               {'variation':['size/Man', '2', '5'], 'quantity':5.5},
               {'variation':['size/Man', '3', '5'], 'quantity':5.75},

               {'variation':['size/Woman', '1', '4'], 'quantity':6.},
               {'variation':['size/Woman', '2', '4'], 'quantity':6.5},
               {'variation':['size/Woman', '3', '4'], 'quantity':7.},
               {'variation':['size/Woman', '1', '5'], 'quantity':7.5},
               {'variation':['size/Woman', '2', '5'], 'quantity':8.},
               {'variation':['size/Woman', '3', '5'], 'quantity':8.5},
             ]
           }, # line end
           {'resource':1, 'cells': [
               {'variation':['size/Man', '3', '4'], 'quantity':6.},
             ]
           }, # line end
629
        ]
Guillaume Michon's avatar
Guillaume Michon committed
630 631 632 633 634 635 636 637 638 639 640 641 642
      }, # packing list end
      { 'source':3, 'destination':9, 'source_section':0, 'destination_section':7,
        'source_payment':1, 'destination_payment':8, 'start_date':DateTime()-10, 'lines':[
           {'resource':0, 'cells': [
               {'variation':['size/Baby', '1', '5'], 'quantity':7.5},
               {'variation':['size/Baby', '2', '5'], 'quantity':5.},
               {'variation':['size/Baby', '3', '5'], 'quantity':3.},
             ]
           }, # line end
           {'resource':2, 'cells': [
               {'variation':['size/Baby', '3', '5'], 'quantity':18.},
             ]
           }, # line end
643
        ]
Guillaume Michon's avatar
Guillaume Michon committed
644 645
      }, # packing list end
    ]
646

Guillaume Michon's avatar
Guillaume Michon committed
647 648 649 650 651 652
    packing_list_list = []
    delivery_line_list = []
    organisation_list = sequence.get('organisation_list')
    resource_list = sequence.get('resource_list')
    order = sequence.get('order')
    packing_list_module = self.getPortal().getDefaultModule(self.packing_list_portal_type)
653

Guillaume Michon's avatar
Guillaume Michon committed
654 655
    for data in data_list:
      # Create Packing List
Julien Muchembled's avatar
Julien Muchembled committed
656 657 658
      packing_list = packing_list_module.newContent(
          portal_type=self.packing_list_portal_type,
          specialise=self.business_process)
Guillaume Michon's avatar
Guillaume Michon committed
659 660 661 662 663 664
      packing_list_list.append(packing_list)
      # Add properties
      property_list = [x for x in data.items() if x[0] not in ('lines','start_date')]
      property_list = [(x[0], organisation_list[x[1]].getRelativeUrl()) for x in property_list] + \
                      [x for x in data.items() if x[0] in ('start_date',)]
      property_dict = {}
665
      property_dict['price_currency'] = self.price_currency
Guillaume Michon's avatar
Guillaume Michon committed
666 667 668 669 670 671 672 673 674 675 676 677 678 679
      for (id, value) in property_list: property_dict[id] = value
      packing_list.edit(**property_dict)
      for line in data['lines']:
        # Create Packing List Line
        packing_list_line = packing_list.newContent(portal_type=self.packing_list_line_portal_type)
        delivery_line_list.append(packing_list_line)
        resource_value = resource_list[line['resource']]
        resource_value.setVariationBaseCategoryList(base_category_list)
        variation_category_list = resource_value.getVariationRangeCategoryList(base_category_list=['size']) + \
            ['colour/' + x.getRelativeUrl() for x in resource_value.objectValues(portal_type='Apparel Model Colour Variation')] + \
            ['morphology/' + x.getRelativeUrl() for x in resource_value.objectValues(portal_type='Apparel Model Morphology Variation')]

        packing_list_line.edit(
            resource_value = resource_value,
680 681
            variation_category_list=variation_category_list
        )
682

Guillaume Michon's avatar
Guillaume Michon committed
683 684 685 686
        # Set cell range
        base_category_dict = {}
        for i in range(len(base_category_list)):
          base_category_dict[base_category_list[i]] = i
687

Guillaume Michon's avatar
Guillaume Michon committed
688 689 690 691 692 693 694 695
        # Set cells
        for cell in line['cells']:
          variation = cell['variation']
          for i in range(len(variation)):
            c = variation[i]
            if len(c.split('/')) == 1:
              variation[i] = '%s/%s' % (base_category_list[i], resource_value[c].getRelativeUrl())
          new_variation = []
696
          self.failUnless(len(packing_list_line.getVariationBaseCategoryList())>0)
Guillaume Michon's avatar
Guillaume Michon committed
697 698 699
          for bc in packing_list_line.getVariationBaseCategoryList():
            new_variation.append(variation[base_category_dict[bc]])
          variation = new_variation
Sebastien Robin's avatar
Sebastien Robin committed
700
          packing_list_cell = packing_list_line.newCell(base_id='movement', *variation)
Guillaume Michon's avatar
Guillaume Michon committed
701 702 703 704 705 706 707
          packing_list_cell.edit(
              quantity = cell['quantity'],
              predicate_category_list = variation,
              variation_category_list = variation,
              mapped_value_property_list = ['quantity'],
              )
    sequence.edit(packing_list_list = packing_list_list)
708

Guillaume Michon's avatar
Guillaume Michon committed
709 710 711 712 713 714 715
  def stepCreateTestingCategories(self, sequence=None, sequence_list=None, **kw):
    """
      Create some categories and affect them to resources and organisations
    """
    category_tool = self.getPortal().portal_categories
    organisation_list = sequence.get('organisation_list')
    resource_list = sequence.get('resource_list')
716

Guillaume Michon's avatar
Guillaume Michon committed
717 718
    bc = category_tool.newContent(portal_type = 'Base Category', id = 'testing_category')
    self.createCategory(bc, ['a', ['aa', 'ab'], 'o', 'z', ['za', 'zb', ['zba', 'zbb'], 'zc'] ])
719
    self.tic()
720

Guillaume Michon's avatar
Guillaume Michon committed
721 722 723 724 725 726 727 728 729 730 731
    category_org_list = [ ['testing_category/a/aa', 'testing_category/o'], # 0
                          ['testing_category/a/aa', 'testing_category/z'], # 1
                          ['testing_category/a/aa', 'testing_category/z/zb/zba'], # 2
                          ['testing_category/a/aa', 'testing_category/z/zb/zbb'], # 3
                          ['testing_category/o', 'testing_category/z'], # 4
                          ['testing_category/z', 'testing_category/z/zc'], # 5
                          ['testing_category/z', 'testing_category/a/ab'],# 6
                          ['testing_category/o', 'testing_category/z/zc'], # 7
                          ['testing_category/z', 'testing_category/a/ab'], # 8
                          ['testing_category/a', 'testing_category/z/zb'],# 9
                        ]
732

Guillaume Michon's avatar
Guillaume Michon committed
733 734 735 736
    category_res_list = [ ['testing_category/a/aa', 'testing_category/z'],
                          ['testing_category/a/aa', 'testing_category/z/za'],
                          ['testing_category/a/aa', 'testing_category/o']
                        ]
737

Guillaume Michon's avatar
Guillaume Michon committed
738 739 740 741 742 743 744 745
    for i in range(len(category_org_list)):
      organisation = organisation_list[i]
      new_categories = category_org_list[i]
      organisation.edit(categories = organisation.getCategoryList() + new_categories)
    for i in range(len(category_res_list)):
      resource = resource_list[i]
      new_categories = category_res_list[i]
      resource.edit(categories = resource.getCategoryList() + new_categories)
746

Guillaume Michon's avatar
Guillaume Michon committed
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774

  def stepTestGetInventoryOnNode(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventory on each node
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':2, 'values':[{'date':DateTime()-28, 'inventory':280.5},
                         {'date':DateTime()-20, 'inventory':280.5},
                         {'date':DateTime()-12, 'inventory':162.},
                         {'date':DateTime(),    'inventory':162.},]
      },
      {'id':3, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':146.},
                         {'date':DateTime()-12, 'inventory':146.},
                         {'date':DateTime(),    'inventory':112.5},]
      },
      {'id':6, 'values':[{'date':DateTime()-28, 'inventory':-280.5},
                         {'date':DateTime()-20, 'inventory':-426.5},
                         {'date':DateTime()-12, 'inventory':-426.5},
                         {'date':DateTime(),    'inventory':-426.5},]
      },
      {'id':9, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':0.},
                         {'date':DateTime()-12, 'inventory':118.5},
                         {'date':DateTime(),    'inventory':152.},]
      },
    ]
775

Guillaume Michon's avatar
Guillaume Michon committed
776 777 778 779 780 781 782 783
    for expected_values in expected_values_list:
      organisation = organisation_list[expected_values['id']]
      url = organisation.getRelativeUrl()
      values = expected_values['values']
      for value in values:
        date = value['date']
        e_inventory = value['inventory']
        self._testGetInventory(expected=e_inventory, at_date=date, node=url)
784

Guillaume Michon's avatar
Guillaume Michon committed
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807

  def stepTestGetInventoryOnPayment(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventory on each payment
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':1, 'values':[{'date':DateTime()-28, 'inventory':280.5},
                         {'date':DateTime()-20, 'inventory':426.5},
                         {'date':DateTime()-12, 'inventory':308.},
                         {'date':DateTime(),    'inventory':274.5},]
      },
      {'id':5, 'values':[{'date':DateTime()-28, 'inventory':-280.5},
                         {'date':DateTime()-20, 'inventory':-426.5},
                         {'date':DateTime()-12, 'inventory':-426.5},
                         {'date':DateTime(),    'inventory':-426.5},]
      },
      {'id':8, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':0.},
                         {'date':DateTime()-12, 'inventory':118.5},
                         {'date':DateTime(),    'inventory':152.},]
      },
    ]
808

Guillaume Michon's avatar
Guillaume Michon committed
809 810 811 812 813 814 815 816
    for expected_values in expected_values_list:
      organisation = organisation_list[expected_values['id']]
      url = organisation.getRelativeUrl()
      values = expected_values['values']
      for value in values:
        date = value['date']
        e_inventory = value['inventory']
        self._testGetInventory(expected=e_inventory, at_date=date, payment=url)
817

Guillaume Michon's avatar
Guillaume Michon committed
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840

  def stepTestGetInventoryOnSection(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventory on each section
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':0, 'values':[{'date':DateTime()-28, 'inventory':280.5},
                         {'date':DateTime()-20, 'inventory':426.5},
                         {'date':DateTime()-12, 'inventory':308.},
                         {'date':DateTime(),    'inventory':274.5},]
      },
      {'id':4, 'values':[{'date':DateTime()-28, 'inventory':-280.5},
                         {'date':DateTime()-20, 'inventory':-426.5},
                         {'date':DateTime()-12, 'inventory':-426.5},
                         {'date':DateTime(),    'inventory':-426.5},]
      },
      {'id':7, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':0.},
                         {'date':DateTime()-12, 'inventory':118.5},
                         {'date':DateTime(),    'inventory':152.},]
      },
    ]
841

Guillaume Michon's avatar
Guillaume Michon committed
842 843 844 845 846 847 848 849
    for expected_values in expected_values_list:
      organisation = organisation_list[expected_values['id']]
      url = organisation.getRelativeUrl()
      values = expected_values['values']
      for value in values:
        date = value['date']
        e_inventory = value['inventory']
        self._testGetInventory(expected=e_inventory, at_date=date, section=url)
850 851


Guillaume Michon's avatar
Guillaume Michon committed
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
  def stepTestGetInventoryOnMirrorSection(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventory on each mirror section
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':0, 'values':[{'date':DateTime()-28, 'inventory':-280.5},
                         {'date':DateTime()-20, 'inventory':-426.5},
                         {'date':DateTime()-12, 'inventory':-308.},
                         {'date':DateTime(),    'inventory':-274.5},]
      },
      {'id':4, 'values':[{'date':DateTime()-28, 'inventory':280.5},
                         {'date':DateTime()-20, 'inventory':426.5},
                         {'date':DateTime()-12, 'inventory':426.5},
                         {'date':DateTime(),    'inventory':426.5},]
      },
      {'id':7, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':0.},
                         {'date':DateTime()-12, 'inventory':-118.5},
                         {'date':DateTime(),    'inventory':-152.},]
      },
    ]
874

Guillaume Michon's avatar
Guillaume Michon committed
875 876 877 878 879 880 881 882
    for expected_values in expected_values_list:
      organisation = organisation_list[expected_values['id']]
      url = organisation.getRelativeUrl()
      values = expected_values['values']
      for value in values:
        date = value['date']
        e_inventory = value['inventory']
        self._testGetInventory(expected=e_inventory, at_date=date, mirror_section=url)
883 884


Guillaume Michon's avatar
Guillaume Michon committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
  def stepTestGetInventoryOnResource(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventory on each resource
    """
    resource_list = sequence.get('resource_list')
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':0, 'values':[{'date':DateTime()-28, 'inventory':232.5},
                         {'date':DateTime()-20, 'inventory':358.5},
                         {'date':DateTime()-12, 'inventory':246.},
                         {'date':DateTime(),    'inventory':230.5},]
      },
      {'id':1, 'values':[{'date':DateTime()-28, 'inventory':31.5},
                         {'date':DateTime()-20, 'inventory':31.5},
                         {'date':DateTime()-12, 'inventory':25.5},
                         {'date':DateTime(),    'inventory':25.5},]
      },
      {'id':2, 'values':[{'date':DateTime()-28, 'inventory':16.5},
                         {'date':DateTime()-20, 'inventory':36.5},
                         {'date':DateTime()-12, 'inventory':36.5},
                         {'date':DateTime(),    'inventory':18.5},]
      },
    ]
908

Guillaume Michon's avatar
Guillaume Michon committed
909 910 911 912 913 914 915 916 917
    organisation_url = organisation_list[0].getRelativeUrl()
    for expected_values in expected_values_list:
      resource = resource_list[expected_values['id']]
      url = resource.getRelativeUrl()
      values = expected_values['values']
      for value in values:
        date = value['date']
        e_inventory = value['inventory']
        self._testGetInventory(expected=e_inventory, at_date=date, resource=url, section=organisation_url)
918 919


Guillaume Michon's avatar
Guillaume Michon committed
920 921
  def stepTestGetInventoryOnVariationText(self, sequence=None, sequence_list=None, **kw):
    """
922

Guillaume Michon's avatar
Guillaume Michon committed
923 924 925 926
    """
    simulation = self.getPortal().portal_simulation
    delivery = sequence.get('packing_list_list')[0]
    expected_values_list = [
Sebastien Robin's avatar
Sebastien Robin committed
927
      {'text':delivery['1']['movement_0_0_0'],
Guillaume Michon's avatar
Guillaume Michon committed
928 929 930
              'values':[{'inventory':17.},]
      },
    ]
931

Guillaume Michon's avatar
Guillaume Michon committed
932 933 934 935 936 937 938 939
    organisation_list = sequence.get('organisation_list')
    organisation_url = organisation_list[0].getRelativeUrl()
    for expected_values in expected_values_list:
      variation_text = expected_values['text'].getVariationText()
      values = expected_values['values']
      for value in values:
        e_inventory = value['inventory']
        self._testGetInventory(expected=e_inventory, variation_text=variation_text, section=organisation_url)
940

941 942
  def stepTestInventoryListBrainGetQuantity(self, sequence=None, sequence_list=None, **kw):
    """
943

944 945 946
    """
    simulation = self.getPortal().portal_simulation
    delivery = sequence.get('packing_list_list')[0]
947

948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
    organisation_list = sequence.get('organisation_list')
    organisation_url = organisation_list[0].getRelativeUrl()
    movement = delivery['1']['movement_0_0_0']
    variation_text = movement.getVariationText()
    inventory_kw = {'section':organisation_url,
                    'variation_text':variation_text}
    simulation = self.getPortal().portal_simulation
    uid = movement.getUid()
    inventory_list = simulation.getInventoryList(**inventory_kw)
    found = 0
    for inventory in inventory_list:
      inventory_object = inventory.getObject()
      if inventory_object.getUid()==uid:
        found=1
        self.assertEquals(inventory_object.getQuantity(), 0.5)
        self.assertEquals(inventory.getQuantity(), 0.5)
    self.failUnless(found==1)

966 967


Guillaume Michon's avatar
Guillaume Michon committed
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
  def stepTestGetInventoryOnVariationCategory(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventory on some variation categories
    """
    resource_list = sequence.get('resource_list')
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':'size/Baby', 'values':[{'date':DateTime()-28, 'inventory':27.},
                                   {'date':DateTime()-20, 'inventory':153.5},
                                   {'date':DateTime()-12, 'inventory':149.75},
                                   {'date':DateTime(),    'inventory':116.25},]
      },
      {'id':'size/Child/32', 'values':[{'date':DateTime()-28, 'inventory':28.5},
                                       {'date':DateTime()-20, 'inventory':28.5},
                                       {'date':DateTime()-12, 'inventory':15.75},
                                       {'date':DateTime(),    'inventory':15.75},]
      },
      {'id':'size/Child/34', 'values':[{'date':DateTime()-28, 'inventory':46.5},
                                       {'date':DateTime()-20, 'inventory':46.5},
                                       {'date':DateTime()-12, 'inventory':24.75},
                                       {'date':DateTime(),    'inventory':24.75},]
      },
      {'id':'size/Man', 'values':[{'date':DateTime()-28, 'inventory':96.},
                                  {'date':DateTime()-20, 'inventory':96.},
                                  {'date':DateTime()-12, 'inventory':59.25},
                                  {'date':DateTime(),    'inventory':59.25},]
      },
      {'id':'size/Woman', 'values':[{'date':DateTime()-28, 'inventory':82.5},
                                    {'date':DateTime()-20, 'inventory':102.},
                                    {'date':DateTime()-12, 'inventory':58.5},
                                    {'date':DateTime(),    'inventory':58.5},]
      },
      {'id':['size/Baby', 'colour/' + resource_list[0]['3'].getRelativeUrl()],
                        'values':[{'date':DateTime()-28, 'inventory':105.},
                                  {'date':DateTime()-20, 'inventory':231.5},
                                  {'date':DateTime()-12, 'inventory':189.},
                                  {'date':DateTime(),    'inventory':155.5},]
      },
      {'id':['size/Man', 'colour/' + resource_list[0]['3'].getRelativeUrl(), 'morphology/' + resource_list[0]['4'].getRelativeUrl()],
                        'values':[{'date':DateTime()-28, 'inventory':204.},
                                  {'date':DateTime()-20, 'inventory':293.5},
                                  {'date':DateTime()-12, 'inventory':204.75},
                                  {'date':DateTime(),    'inventory':201.75},]
      },
1012 1013


Guillaume Michon's avatar
Guillaume Michon committed
1014
    ]
1015

Guillaume Michon's avatar
Guillaume Michon committed
1016 1017 1018 1019 1020 1021 1022
    organisation_url = organisation_list[0].getRelativeUrl()
    for expected_values in expected_values_list:
      category_list = expected_values['id']
      values = expected_values['values']
      for value in values:
        date = value['date']
        e_inventory = value['inventory']
1023 1024 1025 1026
        self._testGetInventory(expected=e_inventory,
                               at_date=date,
                               variation_category=category_list,
                               section=organisation_url)
1027 1028


1029 1030
  def stepTestGetInventoryWithOmitOutput(self, sequence=None,
                                         sequence_list=None, **kw):
Guillaume Michon's avatar
Guillaume Michon committed
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
    """
      Test getInventory on each node with omit_output
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':2, 'values':[{'date':DateTime()-28, 'inventory':280.5},
                         {'date':DateTime()-20, 'inventory':280.5},
                         {'date':DateTime()-12, 'inventory':280.5},
                         {'date':DateTime(),    'inventory':280.5},]
      },
      {'id':3, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':146.},
                         {'date':DateTime()-12, 'inventory':146.},
                         {'date':DateTime(),    'inventory':146.},]
      },
      {'id':6, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':0.},
                         {'date':DateTime()-12, 'inventory':0.},
                         {'date':DateTime(),    'inventory':0.},]
      },
      {'id':9, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':0.},
                         {'date':DateTime()-12, 'inventory':118.5},
                         {'date':DateTime(),    'inventory':152.},]
      },
    ]
1057

Guillaume Michon's avatar
Guillaume Michon committed
1058 1059 1060 1061 1062 1063 1064
    for expected_values in expected_values_list:
      organisation = organisation_list[expected_values['id']]
      url = organisation.getRelativeUrl()
      values = expected_values['values']
      for value in values:
        date = value['date']
        e_inventory = value['inventory']
1065 1066 1067 1068
        self._testGetInventory(expected=e_inventory,
                               at_date=date,
                               node=url,
                               omit_output=1)
1069 1070


Guillaume Michon's avatar
Guillaume Michon committed
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
  def stepTestGetInventoryWithOmitInput(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventory on each node with omit_input
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':2, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':0.},
                         {'date':DateTime()-12, 'inventory':-118.5},
                         {'date':DateTime(),    'inventory':-118.5},]
      },
      {'id':3, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':0.},
                         {'date':DateTime()-12, 'inventory':0.},
                         {'date':DateTime(),    'inventory':-33.5},]
      },
      {'id':6, 'values':[{'date':DateTime()-28, 'inventory':-280.5},
                         {'date':DateTime()-20, 'inventory':-426.5},
                         {'date':DateTime()-12, 'inventory':-426.5},
                         {'date':DateTime(),    'inventory':-426.5},]
      },
      {'id':9, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':0.},
                         {'date':DateTime()-12, 'inventory':0.},
                         {'date':DateTime(),    'inventory':0.},]
      },
    ]
1098

Guillaume Michon's avatar
Guillaume Michon committed
1099 1100 1101 1102 1103 1104 1105
    for expected_values in expected_values_list:
      organisation = organisation_list[expected_values['id']]
      url = organisation.getRelativeUrl()
      values = expected_values['values']
      for value in values:
        date = value['date']
        e_inventory = value['inventory']
1106 1107 1108 1109
        self._testGetInventory(expected=e_inventory,
                               at_date=date,
                               node=url,
                               omit_input=1)
1110

Guillaume Michon's avatar
Guillaume Michon committed
1111

1112 1113
  def stepTestGetInventoryOnSectionCategory(self, sequence=None,
                                            sequence_list=None, **kw):
Guillaume Michon's avatar
Guillaume Michon committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    """
      Test getInventory with a section_category argument
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':'testing_category/a/aa', 'values':[{'inventory':274.5},] },
      {'id':'testing_category/z/zc', 'values':[{'inventory':152.},] },
      {'id':'testing_category/z', 'values':[{'inventory':-274.5},] },
      {'id':'testing_category/o', 'values':[{'inventory':0.},] },
    ]
1124

Guillaume Michon's avatar
Guillaume Michon committed
1125 1126 1127 1128 1129
    for expected_values in expected_values_list:
      category = expected_values['id']
      values = expected_values['values']
      for value in values:
        e_inventory = value['inventory']
1130 1131
        self._testGetInventory(expected=e_inventory,
                               section_category=category)
1132 1133


1134 1135
  def stepTestGetInventoryOnPaymentCategory(self, sequence=None,
                                            sequence_list=None, **kw):
Guillaume Michon's avatar
Guillaume Michon committed
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
    """
      Test getInventory with a payment_category argument
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':'testing_category/a/aa', 'values':[{'inventory':274.5},] },
      {'id':'testing_category/z/zc', 'values':[{'inventory':-426.5},] },
      {'id':'testing_category/a/ab', 'values':[{'inventory':152.},] },
      {'id':'testing_category/a', 'values':[{'inventory':426.5},] },
    ]
1146

Guillaume Michon's avatar
Guillaume Michon committed
1147 1148 1149 1150 1151
    for expected_values in expected_values_list:
      category = expected_values['id']
      values = expected_values['values']
      for value in values:
        e_inventory = value['inventory']
1152 1153
        self._testGetInventory(expected=e_inventory,
                               payment_category=category)
1154 1155


1156 1157
  def stepTestGetInventoryOnNodeCategory(self, sequence=None,
                                         sequence_list=None, **kw):
Guillaume Michon's avatar
Guillaume Michon committed
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
    """
      Test getInventory with a node_category argument
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':'testing_category/z/zb/zba', 'values':[{'inventory':162.},] },
      {'id':'testing_category/z/zb/zbb', 'values':[{'inventory':112.5},] },
      {'id':'testing_category/a/ab', 'values':[{'inventory':-426.5},] },
      {'id':'testing_category/a', 'values':[{'inventory':0.},] },
      {'id':'testing_category/z', 'values':[{'inventory':0.},] },
    ]
1169

Guillaume Michon's avatar
Guillaume Michon committed
1170 1171 1172 1173 1174 1175
    for expected_values in expected_values_list:
      category = expected_values['id']
      values = expected_values['values']
      for value in values:
        e_inventory = value['inventory']
        self._testGetInventory(expected=e_inventory, node_category=category)
1176 1177


Guillaume Michon's avatar
Guillaume Michon committed
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
  def stepTestGetInventoryOnMirrorSectionCategory(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventory with a section_category argument
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':'testing_category/a/aa', 'values':[{'inventory':-274.5},] },
      {'id':'testing_category/z/zc', 'values':[{'inventory':-152.},] },
      {'id':'testing_category/z', 'values':[{'inventory':274.5},] },
      {'id':'testing_category/o', 'values':[{'inventory':0.},] },
    ]
1189

Guillaume Michon's avatar
Guillaume Michon committed
1190 1191 1192 1193 1194 1195
    for expected_values in expected_values_list:
      category = expected_values['id']
      values = expected_values['values']
      for value in values:
        e_inventory = value['inventory']
        self._testGetInventory(expected=e_inventory, mirror_section_category=category)
1196 1197


Guillaume Michon's avatar
Guillaume Michon committed
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
  def stepTestGetInventoryOnResourceCategory(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventory with a resource_category argument
    """
    organisation_list = sequence.get('organisation_list')
    expected_values_list = [
      {'id':'testing_category/a/aa', 'values':[{'inventory':274.5},] },
      {'id':'testing_category/o', 'values':[{'inventory':18.5},] },
      {'id':'testing_category/z/za', 'values':[{'inventory':25.5},] },
      {'id':'testing_category/z', 'values':[{'inventory':256.},] },
    ]
1209

Guillaume Michon's avatar
Guillaume Michon committed
1210 1211 1212 1213 1214
    for expected_values in expected_values_list:
      category = expected_values['id']
      values = expected_values['values']
      for value in values:
        e_inventory = value['inventory']
Jérome Perrin's avatar
Jérome Perrin committed
1215 1216 1217
        self._testGetInventory(expected=e_inventory,
                               resource_category=category,
                               section=organisation_list[0].getRelativeUrl())
1218 1219


Guillaume Michon's avatar
Guillaume Michon committed
1220 1221 1222 1223 1224 1225 1226 1227 1228
  def _testGetInventory(self, expected, **kw):
    """
      Shared testing method
    """
    simulation = self.getPortal().portal_simulation
    e_inventory = expected
    LOG('Testing inventory with args :', 0, kw)
    a_inventory = simulation.getInventory(**kw)
    if e_inventory != a_inventory:
Jérome Perrin's avatar
Jérome Perrin committed
1229 1230 1231
      msg = 'Inventory differs between expected (%s) and real (%s) quantities'\
             % (repr(e_inventory), repr(a_inventory))
      LOG('TestInventory._testGetInventory', 0, msg)
1232
      LOG('SQL Query was : ', 0, str(simulation.getInventory(src__=1, **kw)))
Jérome Perrin's avatar
Jérome Perrin committed
1233
      self.assertEquals(e_inventory, a_inventory, msg)
Guillaume Michon's avatar
Guillaume Michon committed
1234

1235

1236 1237
  def stepTestGetInventoryOnSimulationState(self, sequence=None,
                                            sequence_list=None, **kw):
Guillaume Michon's avatar
Guillaume Michon committed
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
    """
      Test getInventory with some simulation states, by using
      methods getCurrentInventory, getAvailableInventory and getFutureInventory
    """
    packing_list_workflow = 'packing_list_workflow'
    state_variable = 'simulation_state'
    packing_list_list = sequence.get('packing_list_list')
    workflow_tool = self.getPortal().portal_workflow
    simulation = self.getPortal().portal_simulation
    transit_simulation_state = ['started']
1248

Guillaume Michon's avatar
Guillaume Michon committed
1249
    transition_list = [
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
       {'id':0, 'action':'confirm_action'}, # a
       {'id':0, 'action':'set_ready_action'}, # b
              {'id':1, 'action':'confirm_action'}, # c
       {'id':0, 'action':'start_action'}, # d
                     {'id':2, 'action':'confirm_action'}, # e
       {'id':0, 'action':'stop_action'}, # f
                     {'id':2, 'action':'set_ready_action'}, # g
                     {'id':2, 'action':'start_action'}, # h
                            {'id':3, 'action':'confirm_action'}, # i
                            {'id':3, 'action':'set_ready_action'}, # j
                            {'id':3, 'action':'start_action'}, # k
                            {'id':3, 'action':'stop_action'}, # l
Guillaume Michon's avatar
Guillaume Michon committed
1262
    ]
1263

Guillaume Michon's avatar
Guillaume Michon committed
1264 1265
    expected_values_list = [
     #( without omit_transit, with omit_transit)
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
      ({'Current':  0.  , 'Available': 0.  , 'Future':  0.  },
       {'Current':  0.  , 'Available': 0.  , 'Future':  0.  }),
      ({'Current':  0.  , 'Available': 0.  , 'Future':280.5 }, # a
       {'Current':  0.  , 'Available': 0.  , 'Future':280.5 }),
      ({'Current':  0.  , 'Available': 0.  , 'Future':280.5 }, # b
       {'Current':  0.  , 'Available': 0.  , 'Future':280.5 }),
      ({'Current':  0.  , 'Available': 0.  , 'Future':426.5 }, # c
       {'Current':  0.  , 'Available': 0.  , 'Future':426.5 }),
      ({'Current':280.5 , 'Available': 280.5  , 'Future':426.5 }, # d
       {'Current':  0.  , 'Available': 0.  , 'Future':146.  }),
      ({'Current':280.5 , 'Available': 162.  , 'Future':308.  }, # e
       {'Current':  0.  , 'Available': -118.5  , 'Future': 27.5 }),
      ({'Current':280.5 , 'Available': 162.  , 'Future':308.  }, # f
       {'Current':280.5 , 'Available': 162.  , 'Future':308.  }),
      ({'Current':280.5 , 'Available': 162.  , 'Future':308.  }, # g
       {'Current':280.5 , 'Available': 162.  , 'Future':308.  }),
      ({'Current':162.  , 'Available': 162.  , 'Future':308.  }, # h
       {'Current':162.  , 'Available': 162.  , 'Future':308.  }),
      ({'Current':162.  , 'Available': 128.5  , 'Future':274.5 }, # i
       {'Current':162.  , 'Available': 128.5  , 'Future':274.5 }),
      ({'Current':162.  , 'Available': 128.5   , 'Future':274.5 }, # j
       {'Current':162.  , 'Available': 128.5  , 'Future':274.5 }),
      ({'Current':128.5 , 'Available': 128.5  , 'Future':274.5 }, # k
       {'Current':128.5 , 'Available': 128.5  , 'Future':274.5 }),
      ({'Current':128.5 , 'Available': 128.5  , 'Future':274.5 }, # l
       {'Current':128.5 , 'Available': 128.5  , 'Future':274.5 }),
Guillaume Michon's avatar
Guillaume Michon committed
1292
    ]
1293

Guillaume Michon's avatar
Guillaume Michon committed
1294 1295 1296
    organisation_list = sequence.get('organisation_list')
    organisation_url = organisation_list[0].getRelativeUrl()
    date = DateTime()
1297

Guillaume Michon's avatar
Guillaume Michon committed
1298 1299 1300 1301
    def _testWithState(expected_values, omit_transit):
      # Get current workflow states to add it to the log
      state_list = []
      for packing_list in packing_list_list:
Jérome Perrin's avatar
Jérome Perrin committed
1302 1303
        state_list.append(workflow_tool.getStatusOf(
                packing_list_workflow, packing_list)[state_variable])
1304

Guillaume Michon's avatar
Guillaume Michon committed
1305 1306 1307 1308 1309
      LOG('Testing with these workflow states :', 0, state_list)
      for name, e_inventory in expected_values.items():
        method_name = 'get%sInventory' % name
        method = getattr(simulation, method_name, None)
        if method is None:
1310 1311
          LOG('TEST ERROR : Simulation Tool has no %s method'
              % method_name, 0, '')
Guillaume Michon's avatar
Guillaume Michon committed
1312
          self.failUnless(0)
1313
        a_inventory = method(section=organisation_url,
Guillaume Michon's avatar
Guillaume Michon committed
1314 1315 1316 1317 1318
                             omit_transit=omit_transit,
                             transit_simulation_state=transit_simulation_state,
                             at_date=date)
        if a_inventory != e_inventory:
          LOG('TEST ERROR : Inventory quantity differs between expected (%s) and real (%s) quantities' % (repr(e_inventory), repr(a_inventory)), 0, 'with method %s and omit_transit=%s' % (method_name, omit_transit))
1319
          LOG('SQL Query was :', 0, method(section=organisation_url,
Guillaume Michon's avatar
Guillaume Michon committed
1320 1321 1322
                             omit_transit=omit_transit,
                             transit_simulation_state=transit_simulation_state,
                             at_date=date, src__=1))
1323
          self.assertEquals(a_inventory, e_inventory)
1324

Guillaume Michon's avatar
Guillaume Michon committed
1325 1326 1327 1328
    # First, test with draft state everywhere
    LOG('Testing Inventory with every Packing List in draft state...', 0, '')
    for omit_transit in (0,1):
      _testWithState(expected_values_list[0][omit_transit], omit_transit)
1329

Guillaume Michon's avatar
Guillaume Michon committed
1330 1331
    i = 0
    for expected_values in expected_values_list[1:]:
1332 1333 1334
      self.tic() # acceptable here because this is not the job
                 # of the test to check if can do all transition
                 # without processing messages
Guillaume Michon's avatar
Guillaume Michon committed
1335 1336 1337 1338 1339
      transition_step = transition_list[i]
      transited_pl = packing_list_list[transition_step['id']]
      action = transition_step['action']
      LOG("Transiting '%s' on packing list %s" % (action, transition_step['id']), 0, '')
      workflow_tool.doActionFor(transited_pl, action, packing_list_workflow)
1340
      transited_pl.recursiveImmediateReindexObject() # XXX
1341
      self.tic()
1342

Guillaume Michon's avatar
Guillaume Michon committed
1343 1344 1345
      for omit_transit in (0,1):
        values = expected_values[omit_transit]
        _testWithState(values, omit_transit)
1346

Guillaume Michon's avatar
Guillaume Michon committed
1347 1348
      i += 1

1349

Guillaume Michon's avatar
Guillaume Michon committed
1350 1351 1352
  def stepTestGetInventoryWithSelectionReport(self, sequence=None, sequence_list=None, **kw):
    """
    """
1353
    organisation_list = sequence.get('organisation_list')
Guillaume Michon's avatar
Guillaume Michon committed
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
    expected_values_list = [
      {'id':2, 'values':[{'date':DateTime()-28, 'inventory':280.5},
                         {'date':DateTime()-20, 'inventory':280.5},
                         {'date':DateTime()-12, 'inventory':162.},
                         {'date':DateTime(),    'inventory':162.},]
      },
      {'id':3, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':146.},
                         {'date':DateTime()-12, 'inventory':146.},
                         {'date':DateTime(),    'inventory':112.5},]
      },
      {'id':6, 'values':[{'date':DateTime()-28, 'inventory':-280.5},
                         {'date':DateTime()-20, 'inventory':-426.5},
                         {'date':DateTime()-12, 'inventory':-426.5},
                         {'date':DateTime(),    'inventory':-426.5},]
      },
      {'id':9, 'values':[{'date':DateTime()-28, 'inventory':0.},
                         {'date':DateTime()-20, 'inventory':0.},
                         {'date':DateTime()-12, 'inventory':118.5},
                         {'date':DateTime(),    'inventory':152.},]
      },
    ]
1376

1377
    for expected_values in expected_values_list:
1378
      selection_domain = DomainSelection(domain_dict = {'destination_section':organisation_list[expected_values['id']],
1379 1380 1381 1382 1383
                                                        'source_section':organisation_list[expected_values['id']]})
      values = expected_values['values']
      for value in values:
        date = value['date']
        e_inventory = value['inventory']
1384
        self._testGetInventory(expected=e_inventory, at_date=date, selection_domain=selection_domain)
1385 1386


Guillaume Michon's avatar
Guillaume Michon committed
1387 1388 1389 1390 1391 1392
  def stepTestGetInventoryListOnSection(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventoryList on a section
    """
    organisation_list = sequence.get('organisation_list')
    resource_list = sequence.get('resource_list')
1393

Guillaume Michon's avatar
Guillaume Michon committed
1394 1395 1396 1397
    # Build expected list
    expected_list = []
    for i in range(1, 31):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1398 1399 1400 1401
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 0,
                             'inventory': quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1402 1403
    for i in range(31, 33):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1404 1405 1406 1407
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 1,
                             'inventory': quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1408 1409
    for i in range(33, 34):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1410 1411 1412 1413
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 2,
                             'inventory': quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1414 1415
    for i in range(33, 40):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1416 1417 1418 1419
      expected_list.append({ 'node_relative_url': 3,
                             'section_relative_url': 0,
                             'resource_relative_url': 0,
                             'inventory': quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1420 1421
    for i in range(40, 41):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1422 1423 1424 1425
      expected_list.append({ 'node_relative_url': 3,
                             'section_relative_url': 0,
                             'resource_relative_url': 2,
                             'inventory': quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1426 1427
    for i in range(1, 24):
      quantity = (i + 0.) / 4
Jérome Perrin's avatar
Jérome Perrin committed
1428 1429 1430 1431
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 0,
                             'inventory': - quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1432 1433
    for i in range(12, 18):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1434 1435 1436 1437
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 0,
                             'inventory': - quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1438 1439
    for i in range(12, 13):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1440 1441 1442 1443
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 1,
                             'inventory': - quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1444 1445
    for i in [7.5, 5, 3]:
      quantity = (i + 0.)
Jérome Perrin's avatar
Jérome Perrin committed
1446 1447 1448 1449
      expected_list.append({ 'node_relative_url': 3,
                             'section_relative_url': 0,
                             'resource_relative_url': 0,
                             'inventory': - quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1450 1451
    for i in [18]:
      quantity = (i + 0.)
Jérome Perrin's avatar
Jérome Perrin committed
1452 1453 1454 1455 1456
      expected_list.append({ 'node_relative_url': 3,
                             'section_relative_url': 0,
                             'resource_relative_url': 2,
                             'inventory': - quantity })

Guillaume Michon's avatar
Guillaume Michon committed
1457 1458
    for i in [ [2,0,0], [2,0,1], [2,0,2], [3,0,0], [3,0,2],
               [2,0,0], [2,0,1], [3,0,0], [3,0,2] ]:
Jérome Perrin's avatar
Jérome Perrin committed
1459 1460 1461 1462
      expected_list.append({ 'node_relative_url': i[0],
                             'section_relative_url': i[1],
                             'resource_relative_url': i[2],
                             'inventory':0. })
1463

Jérome Perrin's avatar
Jérome Perrin committed
1464 1465 1466
    item_dict = { 'node': organisation_list,
                  'section': organisation_list,
                  'resource': resource_list }
Guillaume Michon's avatar
Guillaume Michon committed
1467 1468
    expected_l = expected_list[:]
    for expected in expected_l:
Jérome Perrin's avatar
Jérome Perrin committed
1469 1470
      for attribute in [x for x in expected.keys()
                          if x.endswith('_relative_url')]:
Guillaume Michon's avatar
Guillaume Michon committed
1471
        attr_name = attribute.split('_')[0]
Jérome Perrin's avatar
Jérome Perrin committed
1472 1473 1474 1475 1476
        expected[attribute] = item_dict[attr_name]\
                                  [expected[attribute]].getRelativeUrl()
    self._testGetInventoryList(expected=expected_l,
                               section=organisation_list[0].getRelativeUrl(),
                               omit_simulation=1)
1477

Jérome Perrin's avatar
Jérome Perrin committed
1478 1479
  def stepTestGetInventoryListOnNode(self, sequence=None,
                                     sequence_list=None, **kw):
Guillaume Michon's avatar
Guillaume Michon committed
1480 1481 1482 1483 1484
    """
      Test getInventoryList on a Node
    """
    organisation_list = sequence.get('organisation_list')
    resource_list = sequence.get('resource_list')
1485

Guillaume Michon's avatar
Guillaume Michon committed
1486 1487 1488 1489
    # Build expected list
    expected_list = []
    for i in range(1, 31):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1490 1491 1492 1493
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 0,
                             'inventory': quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1494 1495
    for i in range(31, 33):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1496 1497 1498 1499
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 1,
                             'inventory': quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1500 1501
    for i in range(33, 34):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1502 1503 1504 1505
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 2,
                             'inventory': quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1506 1507
    for i in range(1, 24):
      quantity = (i + 0.) / 4
Jérome Perrin's avatar
Jérome Perrin committed
1508 1509 1510 1511
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 0,
                             'inventory': - quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1512 1513
    for i in range(12, 18):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1514 1515 1516 1517
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 0,
                             'inventory': - quantity })
Guillaume Michon's avatar
Guillaume Michon committed
1518 1519
    for i in range(12, 13):
      quantity = (i + 0.) / 2
Jérome Perrin's avatar
Jérome Perrin committed
1520 1521 1522 1523 1524
      expected_list.append({ 'node_relative_url': 2,
                             'section_relative_url': 0,
                             'resource_relative_url': 1,
                             'inventory': - quantity })

Guillaume Michon's avatar
Guillaume Michon committed
1525
    for i in [ [2,0,0], [2,0,1], [2,0,2], [2,0,0], [2,0,1] ]:
Jérome Perrin's avatar
Jérome Perrin committed
1526 1527 1528 1529
      expected_list.append({ 'node_relative_url': i[0],
                             'section_relative_url': i[1],
                             'resource_relative_url': i[2],
                             'inventory':0. })
1530

Jérome Perrin's avatar
Jérome Perrin committed
1531 1532 1533
    item_dict = { 'node': organisation_list,
                  'section': organisation_list,
                  'resource': resource_list }
Guillaume Michon's avatar
Guillaume Michon committed
1534 1535
    expected_l = expected_list[:]
    for expected in expected_l:
Jérome Perrin's avatar
Jérome Perrin committed
1536 1537
      for attribute in [x for x in expected.keys()
                            if x.endswith('_relative_url')]:
Guillaume Michon's avatar
Guillaume Michon committed
1538
        attr_name = attribute.split('_')[0]
Jérome Perrin's avatar
Jérome Perrin committed
1539 1540 1541 1542 1543
        expected[attribute] = item_dict[attr_name]\
                                [expected[attribute]].getRelativeUrl()
    self._testGetInventoryList( expected=expected_l,
                                node=organisation_list[2].getRelativeUrl(),
                                omit_simulation=1)
Guillaume Michon's avatar
Guillaume Michon committed
1544

1545

Guillaume Michon's avatar
Guillaume Michon committed
1546 1547 1548 1549 1550 1551
  def stepTestGetInventoryListWithOmitInput(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventoryList on a section with omit_input
    """
    organisation_list = sequence.get('organisation_list')
    resource_list = sequence.get('resource_list')
1552

Guillaume Michon's avatar
Guillaume Michon committed
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
    # Build expected list
    expected_list = []
    for i in range(1, 24):
      quantity = (i + 0.) / 4
      expected_list.append({ 'node_relative_url': 2, 'section_relative_url':0, 'resource_relative_url':0, 'inventory':-quantity })
    for i in range(12, 18):
      quantity = (i + 0.) / 2
      expected_list.append({ 'node_relative_url': 2, 'section_relative_url':0, 'resource_relative_url':0, 'inventory':-quantity })
    for i in range(12, 13):
      quantity = (i + 0.) / 2
      expected_list.append({ 'node_relative_url': 2, 'section_relative_url':0, 'resource_relative_url':1, 'inventory':-quantity })
    for i in [7.5, 5, 3]:
      quantity = (i + 0.)
      expected_list.append({ 'node_relative_url': 3, 'section_relative_url':0, 'resource_relative_url':0, 'inventory':-quantity })
    for i in [18]:
      quantity = (i + 0.)
      expected_list.append({ 'node_relative_url': 3, 'section_relative_url':0, 'resource_relative_url':2, 'inventory':-quantity })
1570

Guillaume Michon's avatar
Guillaume Michon committed
1571 1572 1573 1574 1575 1576 1577
    item_dict = {'node':organisation_list, 'section':organisation_list, 'resource':resource_list}
    expected_l = expected_list[:]
    for expected in expected_l:
      for attribute in [x for x in expected.keys() if x.endswith('_relative_url')]:
        attr_name = attribute.split('_')[0]
        expected[attribute] = item_dict[attr_name][expected[attribute]].getRelativeUrl()
    self._testGetInventoryList(expected=expected_l, section=organisation_list[0].getRelativeUrl(), omit_simulation=1, omit_input=1)
1578 1579


Guillaume Michon's avatar
Guillaume Michon committed
1580 1581 1582 1583 1584 1585
  def stepTestGetInventoryListWithOmitOutput(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventoryList on a section with omit_output
    """
    organisation_list = sequence.get('organisation_list')
    resource_list = sequence.get('resource_list')
1586

Guillaume Michon's avatar
Guillaume Michon committed
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
    # Build expected list
    expected_list = []
    for i in range(1, 31):
      quantity = (i + 0.) / 2
      expected_list.append({ 'node_relative_url': 2, 'section_relative_url':0, 'resource_relative_url':0, 'inventory':quantity })
    for i in range(31, 33):
      quantity = (i + 0.) / 2
      expected_list.append({ 'node_relative_url': 2, 'section_relative_url':0, 'resource_relative_url':1, 'inventory':quantity })
    for i in range(33, 34):
      quantity = (i + 0.) / 2
      expected_list.append({ 'node_relative_url': 2, 'section_relative_url':0, 'resource_relative_url':2, 'inventory':quantity })
    for i in range(33, 40):
      quantity = (i + 0.) / 2
      expected_list.append({ 'node_relative_url': 3, 'section_relative_url':0, 'resource_relative_url':0, 'inventory':quantity })
    for i in range(40, 41):
      quantity = (i + 0.) / 2
      expected_list.append({ 'node_relative_url': 3, 'section_relative_url':0, 'resource_relative_url':2, 'inventory':quantity })
1604

Guillaume Michon's avatar
Guillaume Michon committed
1605 1606 1607 1608 1609 1610 1611
    item_dict = {'node':organisation_list, 'section':organisation_list, 'resource':resource_list}
    expected_l = expected_list[:]
    for expected in expected_l:
      for attribute in [x for x in expected.keys() if x.endswith('_relative_url')]:
        attr_name = attribute.split('_')[0]
        expected[attribute] = item_dict[attr_name][expected[attribute]].getRelativeUrl()
    self._testGetInventoryList(expected=expected_l, section=organisation_list[0].getRelativeUrl(), omit_simulation=1, omit_output=1)
1612 1613


Guillaume Michon's avatar
Guillaume Michon committed
1614 1615 1616 1617 1618 1619
  def stepTestGetInventoryListWithGroupBy(self, sequence=None, sequence_list=None, **kw):
    """
      Test getInventoryList by using group_by_*
    """
    organisation_list = sequence.get('organisation_list')
    resource_list = sequence.get('resource_list')
1620

Guillaume Michon's avatar
Guillaume Michon committed
1621
    # Build expected list
1622 1623
    expected_list_list = [
      ({'group_by_node':1}, [
Guillaume Michon's avatar
Guillaume Michon committed
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
        {'node_relative_url': 2, 'section_relative_url':0, 'resource_relative_url':0, 'inventory':120. },
        {'node_relative_url': 2, 'section_relative_url':0, 'resource_relative_url':1, 'inventory':25.5 },
        {'node_relative_url': 2, 'section_relative_url':0, 'resource_relative_url':2, 'inventory':16.5 },
        {'node_relative_url': 3, 'section_relative_url':0, 'resource_relative_url':0, 'inventory':110.5 },
        {'node_relative_url': 3, 'section_relative_url':0, 'resource_relative_url':2, 'inventory':2. },
        {'node_relative_url': 6, 'section_relative_url':4, 'resource_relative_url':0, 'inventory':-358.5 },
        {'node_relative_url': 6, 'section_relative_url':4, 'resource_relative_url':1, 'inventory':-31.5 },
        {'node_relative_url': 6, 'section_relative_url':4, 'resource_relative_url':2, 'inventory':-36.5 },
        {'node_relative_url': 9, 'section_relative_url':7, 'resource_relative_url':0, 'inventory':128. },
        {'node_relative_url': 9, 'section_relative_url':7, 'resource_relative_url':1, 'inventory':6. },
        {'node_relative_url': 9, 'section_relative_url':7, 'resource_relative_url':2, 'inventory':18. },
      ]),
      ({'group_by_variation':1, 'section':organisation_list[0].getRelativeUrl()}, [
        {'resource_relative_url':0, 'inventory':17. },    # Baby
        {'resource_relative_url':0, 'inventory':17.75 },
        {'resource_relative_url':0, 'inventory':18.5 },
        {'resource_relative_url':0, 'inventory':11.75 },
        {'resource_relative_url':0, 'inventory':15. },
        {'resource_relative_url':0, 'inventory':17.75 },
        {'resource_relative_url':0, 'inventory':2. },     # 32
        {'resource_relative_url':0, 'inventory':2.25 },
        {'resource_relative_url':0, 'inventory':2.5 },
        {'resource_relative_url':0, 'inventory':2.75 },
        {'resource_relative_url':0, 'inventory':3. },
        {'resource_relative_url':0, 'inventory':3.25 },
        {'resource_relative_url':0, 'inventory':3.5 },    # 34
        {'resource_relative_url':0, 'inventory':3.75 },
        {'resource_relative_url':0, 'inventory':4. },
        {'resource_relative_url':0, 'inventory':4.25 },
        {'resource_relative_url':0, 'inventory':4.5 },
        {'resource_relative_url':0, 'inventory':4.75 },
        {'resource_relative_url':0, 'inventory':5. },     # Man
        {'resource_relative_url':0, 'inventory':5.25 },
        {'resource_relative_url':0, 'inventory':5.5 },
        {'resource_relative_url':0, 'inventory':5.75 },
        {'resource_relative_url':0, 'inventory':6. },
        {'resource_relative_url':0, 'inventory':6.25 },
        {'resource_relative_url':0, 'inventory':6.5 },    # Woman
        {'resource_relative_url':0, 'inventory':26. },
        {'resource_relative_url':0, 'inventory':6.5 },
        {'resource_relative_url':0, 'inventory':6.5 },
        {'resource_relative_url':0, 'inventory':6.5 },
        {'resource_relative_url':0, 'inventory':6.5 },
1667
        {'resource_relative_url':0, 'inventory':0.}, #None }, # Sum of lines (quantity of lines is NULL)
1668

Guillaume Michon's avatar
Guillaume Michon committed
1669 1670
        {'resource_relative_url':1, 'inventory':15.5 },
        {'resource_relative_url':1, 'inventory':10. },
1671
        {'resource_relative_url':1, 'inventory':0. }, #None }, # Sum of lines (quantity of lines is ULL)
1672

Guillaume Michon's avatar
Guillaume Michon committed
1673
        {'resource_relative_url':2, 'inventory':18.5 },
1674
        {'resource_relative_url':2, 'inventory':0. }, #None }, # Sum of lines (quantity of lines is NULL)
Guillaume Michon's avatar
Guillaume Michon committed
1675 1676
      ]),
    ]
1677

Guillaume Michon's avatar
Guillaume Michon committed
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
    item_dict = {'node':organisation_list, 'section':organisation_list, 'resource':resource_list}
    for expected_tuple in expected_list_list:
      param, expected_list = expected_tuple
      expected_l = expected_list[:]
      for expected in expected_l:
        for attribute in [x for x in expected.keys() if x.endswith('_relative_url')]:
          attr_name = attribute.split('_')[0]
          expected[attribute] = item_dict[attr_name][expected[attribute]].getRelativeUrl()
      LOG('Testing getInventoryList with', 0, param)
      self._testGetInventoryList(expected=expected_l, omit_simulation=1, **param)
1688 1689


Guillaume Michon's avatar
Guillaume Michon committed
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
  def _testGetInventoryList(self, expected, **kw):
    """
      Shared testing method
      expected is a list of dictionaries containing identifying keys and 'inventory'
    """
    simulation = self.getPortal().portal_simulation
    expected = expected[:]
    if len(expected) > 0:
      attribute_list = [x for x in expected[0].keys() if x != 'inventory']
    else:
      attribute_list = []
1701

Guillaume Michon's avatar
Guillaume Michon committed
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
    LOG('Testing getInventoryList with args :', 0, kw)
    inventory_list = simulation.getInventoryList(**kw)
    for inventory in inventory_list:
      a_attributes = {}
      for attr in attribute_list:
        if not hasattr(inventory, attr):
          LOG('TEST ERROR : Result of getInventoryList has no %s attribute' % attr, 0, '')
          LOG('SQL Query was : ', 0, repr(simulation.getInventoryList(src__=1, **kw)))
          self.failUnless(0)
        a_attributes[attr] = getattr(inventory, attr)
      a_inventory = inventory.inventory
      # Build a function to filter on attributes
      def cmpfunction(item):
        for (key, value) in a_attributes.items():
          if item[key] != value:
            return 0
        return 1
      # Look for lines with the same attributes in expected list
      expected_list = []
      for i in range(len(expected)):
        exp = expected[i]
        if cmpfunction(exp):
          expected_list.append(dict(exp))
          expected_list[-1].update({'id':i})
      # Now, look in these lines for one which has the same inventory
      found_list = filter(lambda x:x['inventory'] == a_inventory, expected_list)
      if len(found_list) == 0:
        LOG('TEST ERROR : Found a line with getInventoryList which is not expected.', 0, 'Found line : %s (inventory : %s) ; expected values with these attributes : %s' % (a_attributes, a_inventory, expected_list))
        LOG('SQL Query was : ', 0, repr(simulation.getInventoryList(src__=1, **kw)))
1731
        self.assertNotEquals(len(found_list), 0)
Guillaume Michon's avatar
Guillaume Michon committed
1732
      found = found_list[0]
1733
      LOG('found a line with inventory =', 0, repr(found['inventory']))
Guillaume Michon's avatar
Guillaume Michon committed
1734 1735 1736 1737
      del expected[found['id']]
    # All inventory lines were found. Now check if some expected values remain
    if len(expected) > 0:
      LOG('TEST ERROR : Not all expected values were matched. Remaining =', 0, expected)
1738
      LOG('SQL Query was : ', 0, str(simulation.getInventoryList(src__=1, **kw)))
1739
      self.failUnless(len(expected), 0)
1740 1741


Guillaume Michon's avatar
Guillaume Michon committed
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
  def stepTestGetNextNegativeInventoryDate(self, sequence=None, sequence_list=None, **kw):
    """
      Test getNextNegativeInventoryDate
    """
    expected_negative_date = addToDate(DateTime())
    base_category_list = ['size', 'colour', 'morphology']
    variation_categories = ['size/Baby', '1', '5'] # size, colour, morphology
    node = 3
    # Set some new deliveries to reach a negative inventory
    # Resource and variation MUST be the same on each new delivery
    data_list = [
      { 'source':node, 'destination':9, 'source_section':0, 'destination_section':7,
        'source_payment':1, 'destination_payment':8, 'start_date':expected_negative_date, 'lines':[
           {'resource':0, 'cells': [
               {'variation':variation_categories, 'quantity':100000.},
             ]
           }, # line end
1759
        ]
Guillaume Michon's avatar
Guillaume Michon committed
1760 1761 1762 1763 1764 1765 1766
      }, # packing list end
      { 'source':6, 'destination':node, 'source_section':4, 'destination_section':0,
        'source_payment':5, 'destination_payment':1, 'start_date':expected_negative_date+5, 'lines':[
           {'resource':0, 'cells': [
               {'variation':variation_categories, 'quantity':100000.},
             ]
           }, # line end
1767
        ]
Guillaume Michon's avatar
Guillaume Michon committed
1768 1769
      }, # packing list end
    ]
1770

Guillaume Michon's avatar
Guillaume Michon committed
1771 1772 1773 1774 1775 1776 1777
    portal = self.getPortal()
    simulation = portal.portal_simulation
    packing_list_module = portal.getDefaultModule(self.packing_list_portal_type)
    packing_list_list = sequence.get('packing_list_list')
    organisation_list = sequence.get('organisation_list')
    resource_list = sequence.get('resource_list')
    delivery_line_list = []
1778

Guillaume Michon's avatar
Guillaume Michon committed
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
    for data in data_list:
      # Create Packing List
      packing_list = packing_list_module.newContent(portal_type=self.packing_list_portal_type)
      packing_list_list.append(packing_list)
      # Add properties
      property_list = [x for x in data.items() if x[0] not in ('lines','start_date')]
      property_list = [(x[0], organisation_list[x[1]].getRelativeUrl()) for x in property_list] + \
                      [x for x in data.items() if x[0] in ('start_date',)]
      property_dict = {}
      for (id, value) in property_list: property_dict[id] = value
      packing_list.edit(**property_dict)
      for line in data['lines']:
        # Create Packing List Line
        packing_list_line = packing_list.newContent(portal_type=self.packing_list_line_portal_type)
        delivery_line_list.append(packing_list_line)
        resource_value = resource_list[line['resource']]
        resource_value.setVariationBaseCategoryList(base_category_list)
        category_list = packing_list_line.getCategoryList()
        variation_category_list = resource_value.getVariationRangeCategoryList(base_category_list=['size']) + \
            ['colour/' + x.getRelativeUrl() for x in resource_value.objectValues(portal_type='Apparel Model Colour Variation')] + \
            ['morphology/' + x.getRelativeUrl() for x in resource_value.objectValues(portal_type='Apparel Model Morphology Variation')]

        packing_list_line.edit(
1802 1803 1804
            resource_value=resource_value,
            variation_category_list=variation_category_list,
        )
1805

Guillaume Michon's avatar
Guillaume Michon committed
1806 1807 1808 1809
        # Set cell range
        base_category_dict = {}
        for i in range(len(base_category_list)):
          base_category_dict[base_category_list[i]] = i
1810

Guillaume Michon's avatar
Guillaume Michon committed
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
        # Set cells
        for cell in line['cells']:
          variation = cell['variation']
          for i in range(len(variation)):
            c = variation[i]
            if len(c.split('/')) == 1:
              variation[i] = '%s/%s' % (base_category_list[i], resource_value[c].getRelativeUrl())
          new_variation = []
          for bc in packing_list_line.getVariationBaseCategoryList():
            new_variation.append(variation[base_category_dict[bc]])
          variation = new_variation
Sebastien Robin's avatar
Sebastien Robin committed
1822
          packing_list_cell = packing_list_line.newCell(base_id='movement', *variation)
Guillaume Michon's avatar
Guillaume Michon committed
1823 1824 1825 1826 1827 1828 1829
          packing_list_cell.edit(
              quantity = cell['quantity'],
              predicate_category_list = variation,
              variation_category_list = variation,
              mapped_value_property_list = ['quantity'],
              )
      sequence.edit(packing_list_list = packing_list_list)
1830

1831
    self.tic()
1832

Guillaume Michon's avatar
Guillaume Michon committed
1833
    # Then test the next negative date
Jérome Perrin's avatar
Jérome Perrin committed
1834 1835 1836 1837 1838
    next_date = simulation.getNextNegativeInventoryDate(
                      resource=resource_value.getRelativeUrl(),
                      node=organisation_list[node].getRelativeUrl(),
                      variation_category=variation_categories)

1839 1840
    if type(next_date) == type(''):
      next_date = DateTime(next_date)
1841
    next_date = next_date.strftime('%Y-%m-%d %H:%M:%S')
Jérome Perrin's avatar
Jérome Perrin committed
1842 1843 1844 1845 1846 1847 1848
    expected_negative_date = '%.4d-%.2d-%.2d %.2d:%.2d:%.2d' % (
                            expected_negative_date.year(),
                            expected_negative_date.month(),
                            expected_negative_date.day(),
                            expected_negative_date.hour(),
                            expected_negative_date.minute(),
                            expected_negative_date.second())
Guillaume Michon's avatar
Guillaume Michon committed
1849
    if next_date != expected_negative_date:
Jérome Perrin's avatar
Jérome Perrin committed
1850 1851 1852 1853 1854 1855 1856 1857 1858
      LOG('TEST ERROR : Next negative date is not the expected one.', 0,
          'calculated : %s, expected : %s' % (
           repr(next_date), repr(expected_negative_date)))
      LOG('SQL Query was ', 0,
          simulation.getNextNegativeInventoryDate(
                    resource=resource_value.getRelativeUrl(),
                    node=organisation_list[node].getRelativeUrl(),
                    variation_category=variation_categories, src__=1))
    self.assertEquals(next_date, expected_negative_date)
1859 1860


1861
  def checkVariatedInventory(self, sequence=None, sequence_list=None,
1862 1863 1864 1865 1866 1867 1868 1869 1870
                             variation_category_list=None,
                             quantity=None,**kw):
    """
    """
    simulation = self.getPortal().portal_simulation
    variation_category_list = copy(variation_category_list)
    variation_category_list.sort()
    variation_text = '\n'.join(variation_category_list)
    inventory = simulation.getCurrentInventory(
1871 1872 1873 1874 1875
      resource = sequence.get("resource").getRelativeUrl(),
      section = sequence.get('section').getRelativeUrl(),
      node = sequence.get('node').getRelativeUrl(),
      variation_text = variation_text
      )
1876
    self.assertEquals(inventory, quantity)
1877

1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
  def stepTestInitialVariatedInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Test Inventory Module behavior
    """
    resource = sequence.get('resource')
    variation_category_list = sequence.get('variation_1')
    quantity = 1
    self.checkVariatedInventory(variation_category_list=variation_category_list,
                                quantity=quantity,sequence=sequence)
    variation_category_list = sequence.get('variation_2')
    quantity = 3
    self.checkVariatedInventory(variation_category_list=variation_category_list,
                                quantity=quantity,sequence=sequence)

1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
  def stepTestInitialVariatedNonDefaultQuantityUnitInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Test Inventory Module behavior
    """
    resource = sequence.get('resource')
    variation_category_list = sequence.get('variation_1')
    quantity = 100
    self.checkVariatedInventory(variation_category_list=variation_category_list,
                                quantity=quantity,sequence=sequence)
    variation_category_list = sequence.get('variation_2')
    quantity = 300
    self.checkVariatedInventory(variation_category_list=variation_category_list,
                                quantity=quantity,sequence=sequence)

1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
  def stepTestVariatedInventoryAfterInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Test Inventory Module behavior
    """
    resource = sequence.get('resource')
    variation_category_list = sequence.get('variation_1')
    quantity = 5
    self.checkVariatedInventory(variation_category_list=variation_category_list,
                                quantity=quantity,sequence=sequence)
    variation_category_list = sequence.get('variation_2')
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
    quantity = 3
    self.checkVariatedInventory(variation_category_list=variation_category_list,
                                quantity=quantity,sequence=sequence)

  def stepTestVariatedInventoryNonDefaultQuantityUnitAfterInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Test Inventory Module behavior
    """
    resource = sequence.get('resource')
    variation_category_list = sequence.get('variation_1')
    quantity = 5
    self.checkVariatedInventory(variation_category_list=variation_category_list,
                                quantity=quantity,sequence=sequence)
    variation_category_list = sequence.get('variation_2')
    quantity = 300
    self.checkVariatedInventory(variation_category_list=variation_category_list,
                                quantity=quantity,sequence=sequence)

  def stepTestFullVariatedInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Test full inventory with variated resource
    """
    resource = sequence.get('resource')
    variation_category_list = sequence.get('variation_1')
    # Test first resource
    quantity = 55
    self.checkVariatedInventory(variation_category_list=variation_category_list,
                                quantity=quantity,sequence=sequence)
    variation_category_list = sequence.get('variation_2')
1945 1946 1947 1948
    quantity = 0
    self.checkVariatedInventory(variation_category_list=variation_category_list,
                                quantity=quantity,sequence=sequence)

1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
    # second resource, must be 101
    simulation = self.getPortal().portal_simulation
    inventory = simulation.getCurrentInventory(
      resource = sequence.get("second_resource").getRelativeUrl(),
      section = sequence.get('section').getRelativeUrl(),
      node = sequence.get('node').getRelativeUrl(),
      )
    self.assertEquals(inventory, 101.,
                    'section=%s, node=%s' % (
                    sequence.get('section').getRelativeUrl(),
                    sequence.get('node').getRelativeUrl()))

1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
  def stepTestInventoryModule(self, sequence=None, sequence_list=None, **kw):
    """
      Test Inventory Module behavior
    """
    step = sequence.get('step')
    inventory_list = sequence.get('inventory_list')
    simulation = self.getPortal().portal_simulation
    if step is None:
      step = 0
    expected = [(40.,0), (24.,1), (80.,0)]
1971 1972 1973 1974 1975
    inventory = simulation.getCurrentInventory(
                    section=sequence.get('section').getRelativeUrl(),
                    node=sequence.get('node').getRelativeUrl(),
                    at_date=inventory_list[expected[step][1]].getStartDate()
                )
Jérome Perrin's avatar
Jérome Perrin committed
1976 1977 1978 1979 1980
    self.assertEquals(inventory, expected[step][0],
                    'section=%s, node=%s' % (
                    sequence.get('section').getRelativeUrl(),
                    sequence.get('node').getRelativeUrl()))
    step += 1
1981
    sequence.edit(step=step)
1982

1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
  def stepTestFullInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Test Full inventory behavior
    """
    inventory_list = sequence.get('inventory_list')
    simulation = self.getPortal().portal_simulation

    # First resource, must be zero
    inventory = simulation.getCurrentInventory(
      resource = sequence.get("resource").getRelativeUrl(),
      section = sequence.get('section').getRelativeUrl(),
      node = sequence.get('node').getRelativeUrl(),
      )
    self.assertEquals(inventory, 0.,
                    'section=%s, node=%s' % (
                    sequence.get('section').getRelativeUrl(),
                    sequence.get('node').getRelativeUrl()))
    # second resource, must be 101
    inventory = simulation.getCurrentInventory(
      resource = sequence.get("second_resource").getRelativeUrl(),
      section = sequence.get('section').getRelativeUrl(),
      node = sequence.get('node').getRelativeUrl(),
      )
    self.assertEquals(inventory, 101.,
                    'section=%s, node=%s' % (
                    sequence.get('section').getRelativeUrl(),
                    sequence.get('node').getRelativeUrl()))



2013 2014 2015 2016 2017 2018 2019
  def stepModifyFirstInventory(self, sequence=None, sequence_list=None, **kw):
    """
      Modify the first entered Inventory, to test the quantity change
    """
    inventory = sequence.get('inventory_list')[0]
    inventory_line = inventory['1']
    item_list = sequence.get('item_list')
2020
    aggregate_value_list = [item_list[0],item_list[1], item_list[4]]
Jérome Perrin's avatar
Jérome Perrin committed
2021
    inventory_line.edit(
2022 2023
        aggregate_value_list=aggregate_value_list,
        quantity=sum([x.getQuantity() for x in aggregate_value_list]))
2024 2025


2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
  def stepCreateNotVariatedSecondResource(self,sequence=None,
                                          sequence_list=None,
                                          **kw):
    """
      Create a second resource with no variation
    """
    portal = self.getPortal()
    resource_module = portal.getDefaultModule(self.resource_portal_type)
    resource = resource_module.newContent(portal_type=self.resource_portal_type)
    resource.edit(
      title = "NotVariatedSecondResource%s" % resource.getId(),
      industrial_phase_list=["phase1", "phase2"],
      product_line = 'apparel'
    )

    sequence.edit( second_resource = resource )
    resource_list = sequence.get('resource_list',default=[])
    resource_list.append(resource)
    sequence.edit( resource_list = resource_list )

2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
  def stepSetTwoLevelProductLineOnFirstResource(self,
                                                sequence=None,
                                                sequence_list=None,
                                                **kw):
    """ Create a resource which has two level product_line """
    category_tool = self.portal.portal_categories
    pl = category_tool.product_line
    self.createCategory(pl, ['level1', ['level2']])
    product_module = self.portal.product_module
    resource_value = product_module.newContent(title='Resource',
                                               portal_type='Product')
    resource_value.setProductLine('level1/level2')
    sequence.edit(first_resource=resource_value)


  def stepCreateTwoResourceFullInventory(self,
                                         sequence=None,
                                         sequence_list=None,
                                         **kw):
    """ Create a full Inventory which includes two inventory lines """
    inventory = self.createInventory(sequence=sequence)
    inventory_list = sequence.get('inventory_list',[])
    inventory.edit(full_inventory=True)
    inventory_line = inventory.newContent(
      portal_type = self.inventory_line_portal_type,
      resource_value = sequence.get("first_resource"),
      inventory = 10)
    inventory_line = inventory.newContent(
      portal_type = self.inventory_line_portal_type,
      resource_value = sequence.get("second_resource"),
      inventory = 100)
    inventory.deliver()
    inventory_list.append(inventory)
    sequence.edit(inventory_list=inventory_list)

  def stepTestFullInventoryWithResourceCategory(self,
                                                sequence=None,
                                                sequence_list=None,
                                                **kw):
    """
     Make sure that we can use resource_category parameter with Full inventory.
    """
    node = sequence.get('node')
    section = sequence.get('section')
    getInventory = self.getSimulationTool().getInventory
    self.assertEquals(10, getInventory(section_uid=section.getUid(),
                                        node_uid=node.getUid(),
                                        resource_category='product_line/level1',
                                        optimisation__=False))
    self.assertEquals(10, getInventory(section_uid=section.getUid(),
                                        node_uid=node.getUid(),
                                        resource_category='product_line/level1',
                                        optimisation__=True))
    self.assertEquals(100, getInventory(section_uid=section.getUid(),
                                        node_uid=node.getUid(),
                                        resource_category='product_line/apparel',
                                        optimisation__=False))
    self.assertEquals(100, getInventory(section_uid=section.getUid(),
                                        node_uid=node.getUid(),
                                        resource_category='product_line/apparel',
                                        optimisation__=True))

  def stepSetUpInventoryIndexingByNodeAndSection(self,
                                                 sequence=None,
                                                 sequence_list=None,
                                                 **kw):
    script_name = 'Inventory_getDefaultInventoryCalculationList'
    if script_name in self.portal.portal_skins.custom:
      return
    createZODBPythonScript(self.portal.portal_skins.custom,
                           'Inventory_getDefaultInventoryCalculationList', '',
    dedent('''
    return ({'inventory_params':{
             'section_uid':context.getDestinationSectionUid(),
             'node_uid':context.getDestinationUid(),
             'group_by_variation':1,
             'group_by_resource':1},
            'list_method':'getMovementList',
            'first_level':({'key':'resource_relative_url',
                            'getter':'getResource',
                            'setter':('appendToCategoryList', 'resource')},
                           {'key':'variation_text',
                            'getter':'getVariationText',
                            'setter':'splitAndExtendToCategoryList'},
                           ),
2131 2132 2133 2134
            "second_level":({'key' : 'sub_variation_text',
                             'getter' : 'getSubVariationText',
                             'setter' : "splitAndExtendToCategoryList"},
                            ),
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
            },)
    '''))


  def stepSetTwoLevelGroupOnSection(self,
                                    sequence=None,
                                    sequence_list=None,
                                    **kw):
    """ Create a section which has two level group """
    category_tool = self.portal.portal_categories
    self.createCategory(category_tool.group, ['level1', ['level2']])
    organisation_module = self.portal.organisation_module
    section_value = organisation_module.newContent(title='Organisation',
                                                   portal_type='Organisation')
    section_value.setGroup('level1/level2')
    sequence.edit(section=section_value)

  def stepTestFullInventoryWithSectionCategory(self,
                                               sequence=None,
                                               sequence_list=None,
                                               **kw):
    """
     Make sure that we can use section_category parameter with Full inventory.
    """
    node = sequence.get('node')
    section = sequence.get('section')
    getInventory = self.getSimulationTool().getInventory
    self.assertEquals(202, getInventory(node_uid=node.getUid()))
    self.assertEquals(101, getInventory(section_category='group/level1/level2',
                                        node_uid=node.getUid(),
                                        optimisation__=False))
    self.assertEquals(101, getInventory(node_uid=node.getUid(),
                                        section_category='group/level1/level2',
                                        optimisation__=True))

  def stepSetTwoLevelRegionOnNode(self,
                                  sequence=None,
                                  sequence_list=None,
                                  **kw):
    """ Create a node which has two tier region """
    category_tool = self.portal.portal_categories
    self.createCategory(category_tool.region, ['level1', ['level2']])
    organisation_module = self.portal.organisation_module
    node_value = organisation_module.newContent(title='Organisation',
                                                portal_type='Organisation')
    node_value.setRegion('level1/level2')
    sequence.edit(node=node_value)

  def stepTestFullInventoryWithNodeCategory(self,
                                            sequence=None,
                                            sequence_list=None,
                                            **kw):
    """
     Make sure that we can use node_category parameter with Full inventory.
    """
    node = sequence.get('node')
    section = sequence.get('section')
    getInventory = self.getSimulationTool().getInventory
    self.assertEquals(202, getInventory(section_uid=section.getUid()))
    self.assertEquals(101, getInventory(section_uid=section.getUid(),
                                        node_category='region/level1/level2',
                                        optimisation__=False))
    self.assertEquals(101, getInventory(section_uid=section.getUid(),
                                        node_category='region/level1/level2',
                                        optimisation__=True))

2201 2202
  def stepCreateFullInventoryAtTheDate(self, sequence=None,
                                       sequence_list=None, **kw):
2203
    """ Create Full Inventory at the date' """
2204
    inventory_list = sequence.get('inventory_list',[])
2205 2206 2207 2208
    if kw.get('start_date', None) is not None:
      start_date = kw['start_date']
    else:
      start_date = '2013/03/12 00:00:00 GMT+9'
2209 2210 2211 2212
    if kw.get('resource_value', None) is not None:
      resource_value = kw['resource_value']
    else:
      resource_value = sequence.get('resource')
2213 2214 2215 2216
    if kw.get('destination_value', None) is not None:
      destination_value = kw['destination_value']
    else:
      destination_value = sequence.get('node')
2217 2218 2219
    inventory = self.createInventory(sequence=sequence)
    inventory.edit(full_inventory=True,
                   destination_section_value=sequence.get('section'),
2220
                   destination_value=destination_value,
2221
                   start_date=start_date)
2222 2223
    inventory_line = inventory.newContent(
      portal_type = self.inventory_line_portal_type,
2224
      resource_value = resource_value,
2225 2226 2227 2228 2229 2230
      inventory = 100)
    inventory.deliver()
    inventory_list.append(inventory)
    sequence.edit(inventory_list=inventory_list)


2231 2232
  def stepCreateFullInventoryAtTheDate1(self, sequence=None,
                                        sequence_list=None, **kw):
2233 2234
    if getattr(self, 'full_inventory_start_date_1', None) is None:
      raise UnboundLocalError('Please assign self.full_inventory_start_date_1 '
2235
                              'in your test method')
2236 2237
    params = dict(start_date=self.full_inventory_start_date_1)
    if getattr(self, 'full_inventory_resource_1', None) is not None:
2238
      self.assertNotEquals(sequence.get(self.full_inventory_resource_1), None)
2239
      params['resource_value'] = sequence.get(self.full_inventory_resource_1)
2240 2241 2242
    if getattr(self, 'full_inventory_node_1', None) is not None:
      self.assertNotEquals(sequence.get(self.full_inventory_node_1), None)
      params['destination_value'] = sequence.get(self.full_inventory_node_1)
2243
    self.stepCreateFullInventoryAtTheDate(sequence, sequence_list, **params)
2244

2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
  def stepCreateFullInventoryAtTheDate2(self, sequence=None,
                                        sequence_list=None, **kw):
    if getattr(self, 'full_inventory_start_date_2', None) is None:
      raise UnboundLocalError('Please assign self.full_inventory_start_date_2 '
                              'in your test method')
    params = dict(start_date=self.full_inventory_start_date_2)
    if getattr(self, 'full_inventory_resource_2', None) is not None:
      self.assertNotEquals(sequence.get(self.full_inventory_resource_2), None)
      params['resource_value'] = sequence.get(self.full_inventory_resource_2)
    if getattr(self, 'full_inventory_node_2', None) is not None:
      self.assertNotEquals(sequence.get(self.full_inventory_node_2), None)
      params['destination_value'] = sequence.get(self.full_inventory_node_2)
    self.stepCreateFullInventoryAtTheDate(sequence, sequence_list, **params)

2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321
  def stepCheckMultipleSectionAndFullInventory(self, sequence=None,
                                               sequence_list=None, **kw):
    """ Check that getInvetory() is surely working in
    MultipleSectionAndFullInventory case """
    section = sequence.get('section')
    other_section  = sequence.get('other_section')
    self._testGetInventory(expected=102, section_uid=section.getUid())
    self._testGetInventory(expected=7, section_uid=other_section.getUid())


  def stepCreatePackingListForMultipleSectionAndFullInventory(
        self, sequence=None, sequence_list=None, **kw):
    """ Create packing lists for MultipleSectionAndFullInventory Test """
    node = sequence.get('node')
    section = sequence.get('section')
    mirror_node = sequence.get('mirror_node')
    mirror_section = sequence.get('mirror_section')
    other_section = sequence.get('other_section')
    resource = sequence.get('resource')
    packing_list_module = self.getPortal().getDefaultModule(
                              portal_type=self.packing_list_portal_type)
    movement_list = [
      dict(start_date='2013/03/10 00:00:00 GMT+9',
           destination_section_value=section, quantity=1),
      dict(start_date='2013/03/13 00:00:00 GMT+9',
           destination_section_value=section, quantity=2),
      dict(start_date='2013/03/11 00:00:00 GMT+9',
           destination_section_value=other_section, quantity=3),
      dict(start_date='2013/03/12 00:00:00 GMT+9',
           destination_section_value=other_section, quantity=4)]
    packing_list_list = []
    for movement in movement_list:
      packing_list = packing_list_module.newContent(
                              portal_type=self.packing_list_portal_type)
      packing_list.edit(specialise=self.business_process,
                        source_section_value=mirror_section,
                        source_value=mirror_node,
                        destination_section_value= \
                          movement['destination_section_value'],
                        destination_value=node,
                        start_date=movement['start_date'],
                        price_currency=self.price_currency)
      self.assertNotEquals(packing_list.getSourceSectionValue(), None)
      self.assertNotEquals(packing_list.getSourceValue(), None)
      self.assertNotEquals(packing_list.getSourceSectionValue(),
                           packing_list.getDestinationSectionValue())

      line = packing_list.newContent(
        portal_type=self.packing_list_line_portal_type)
      line.edit(resource_value=resource, quantity=movement['quantity'])
      packing_list_list.append(packing_list)
    sequence.edit(packing_list_list=packing_list_list)

  def stepDeliverAllPackingList(self, sequence=None,
                                      sequence_list=None, **kw):
    """Deliver all the packing lists that are created by test sequences"""
    packing_list_list = sequence.get('packing_list_list')
    for packing_list in packing_list_list:
      for action in ('confirm', 'setReady', 'start', 'stop', 'deliver'):
        workflow_action = getattr(packing_list, action)
        workflow_action()
        self.tic()

2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
  def stepCreatePackingListAtTheDate1(self,
                                     sequence=None,
                                     sequence_list=None,
                                     **kw):
    """ Create Packing List with self.start_date_1"""
    if getattr(self, 'start_date_1', None) is None:
      raise UnboundLocalError('Please Assign self.start_date_1 '
                              'in your test method')
    self.stepCreatePackingListForModule(sequence=sequence,
                                        sequence_list=sequence_list,
2332
                                        start_date=self.start_date_1)
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343

  def stepCreatePackingListAtTheDate2(self,
                                     sequence=None,
                                     sequence_list=None,
                                     **kw):
    """ Create Packing List with self.start_date_2"""
    if getattr(self, 'start_date_2', None) is None:
      raise UnboundLocalError('Please Assign self.start_date_2 '
                              'in your test method')
    self.stepCreatePackingListForModule(sequence=sequence,
                                        sequence_list=sequence_list,
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
                                        start_date=self.start_date_2)

  def stepCreatePackingListLineWithResource1(self,
                                             sequence=None,
                                             sequence_list=None,
                                             **kw):
    """ Create Packing List Line with self.resrouce_1"""
    if getattr(self, 'resource_1', None) is None:
      raise UnboundLocalError('Please Assign self.resource_1 '
                              'in your test method')
    resource_value = sequence.get(self.resource_1)
    self.assertNotEquals(resource_value, None)
    self.stepCreatePackingListLine(sequence=sequence,
                                   sequence_list=sequence_list,
                                   resource_value=resource_value)

  def stepCreatePackingListLineWithResource2(self,
                                             sequence=None,
                                             sequence_list=None,
                                             **kw):
    """ Create Packing List Line with self.resrouce_2"""
    if getattr(self, 'resource_2', None) is None:
      raise UnboundLocalError('Please Assign self.resource_2 '
                              'in your test method')
    resource_value = sequence.get(self.resource_2)
    self.assertNotEquals(resource_value, None)
    self.stepCreatePackingListLine(sequence=sequence,
                                   sequence_list=sequence_list,
                                   resource_value=resource_value)

2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413

  def _testGetMovementHistoryList(self, expected_history=None, **kw):
    """ Helper method to check getMovementHistoryList """
    simulation = self.getPortal().portal_simulation
    LOG('Testing movement history with args :', 0, kw)
    result = simulation.getMovementHistoryList(**kw)
    self.assertTrue(len(result) > 0)
    # Note: Now only checking total_quantity but can be checked more
    actual_history = [{'total_quantity':x.total_quantity} for x in result]
    try:
      self.assertEquals(len(expected_history), len(actual_history))
      for expected, actual in zip(expected_history, actual_history):
        shared_keys = set(expected.keys()) & set(actual.keys())
        self.assertEquals(len(shared_keys), len(expected.keys()))
        shared_item = set(expected.items()) & set(actual.items())
        self.assertEquals(len(shared_item), len(expected.keys()))
    except AssertionError:
      msg = 'History differs between expected:\n%s\nand real:\n%s'\
             % (repr(expected_history), repr(actual_history))
      LOG('TestInventory._testGetMovementHistoryList', 0, msg)
      LOG('SQL Query was : ', 0,
         str(simulation.getMovementHistoryList(src__=1, **kw)))
      raise AssertionError(msg)

  def stepCheckFullInventoryAddOldMovement(self,
                                           sequence=None,
                                           sequence_list=None,
                                           **kw):
    """ Check Create Full Inventory Then Add Old Movement use case """
    section = sequence.get('section')
    node  = sequence.get('node')
    self._testGetInventory(expected=100,
                           section_uid=section.getUid(),
                           node_uid=node.getUid())
    self._testGetMovementHistoryList(expected_history=[{'total_quantity':-100},
                                                       {'total_quantity':100},
                                                       {'total_quantity':100},],
                              section_uid=section.getUid(),
                              node_uid=node.getUid())

2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
  def stepCreateInventoryAtTheDate(self, sequence=None,
                                   sequence_list=None, **kw):
    """ Create Inventory at the date with some flexible variables """
    inventory_quantity = kw['inventory'] if 'inventory' in kw else 100
    start_date = kw['start_date'] if 'start_date' in kw else None
    if 'resource_value' in kw:
      resource_value = kw['resource_value']
    else:
      resource_value = sequence.get('second_resource')
    inventory = self.createInventory(sequence=sequence,
                                     full=False, start_date=start_date)
    inventory_list = sequence.get('inventory_list',[])
    inventory_line = inventory.newContent(
      portal_type=self.inventory_line_portal_type,
      resource_value=resource_value,
      inventory=inventory_quantity)
    inventory.deliver()
    inventory_list.append(inventory)
    sequence.edit(inventory_list=inventory_list)

  def stepCreateInventoryAtTheDate1(self, sequence=None,
                                    sequence_list=None, **kw):
    """ Create Inventory at the date:'self.inventory_start_date_1'
     with some flexible variables """
    if getattr(self, 'inventory_start_date_1', None) is None:
      raise UnboundLocalError('Please assign self.inventory_start_date_1 '
                              'in your test method')
    params = dict(start_date=self.inventory_start_date_1)
    if getattr(self, 'inventory_1', None) is not None:
      params['inventory'] = self.inventory_1
    if getattr(self, 'inventory_resource_1', None) is not None:
      params['resource_value'] = sequence.get(self.inventory_resource_1)

    self.stepCreateInventoryAtTheDate(sequence, sequence_list, **params)

  def stepCreateInventoryAtTheDate2(self, sequence=None,
                                    sequence_list=None, **kw):
    """ Create Inventory at the date:'self.inventory_start_date_2'
     with some flexible variables """
    if getattr(self, 'inventory_start_date_2', None) is None:
      raise UnboundLocalError('Please assign self.inventory_start_date_2 '
                              'in your test method')
    params = dict(start_date=self.inventory_start_date_2)
    if getattr(self, 'inventory_2', None) is not None:
      params['inventory'] = self.inventory_2
    if getattr(self, 'inventory_resource_2', None) is not None:
      params['resource_value'] = sequence.get(self.inventory_resource_2)
    self.stepCreateInventoryAtTheDate(sequence, sequence_list, **params)

  def stepCheckUseBothFullAndPartialInventory(
        self, sequence=None, sequence_list=None, **kw):
    """ Check a case Using both Full and Normal Inventory"""
    resource_value = sequence.get('second_resource')
    node_value = sequence.get('node')
    section_value = sequence.get('section')
    self._testGetInventory(expected=3,
                           section_uid=section_value.getUid(),
                           node_uid=node_value.getUid(),
                           resource_uid=resource_value.getUid())
    self._testGetInventory(expected=3,
                           resource_uid=resource_value.getUid(),
                           optimise__=False)

2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
  def stepTestFullInventoryMultipleNodeAndResource(
        self, sequence=None, sequence_list=None, **kw):
    """ Test Full inventory with multiple nodes and resources"""
    resource_value = sequence.get('resource')
    second_resource_value = sequence.get('second_resource')
    node_value = sequence.get('node')
    other_node_value = sequence.get('other_node')
    section_value = sequence.get('section')
    self._testGetInventory(expected=100,
                           section_uid=section_value.getUid(),
                           node_uid=node_value.getUid(),
                           resource_uid=resource_value.getUid())
    self._testGetInventory(expected=100,
                           section_uid=section_value.getUid(),
                           node_uid=node_value.getUid(),
                           resource_uid=second_resource_value.getUid())
    self._testGetInventory(expected=100,
                           section_uid=section_value.getUid(),
                           node_uid=other_node_value.getUid(),
                           resource_uid=second_resource_value.getUid())
    self._testGetInventory(expected=0,
                           section_uid=section_value.getUid(),
                           node_uid=other_node_value.getUid(),
                           resource_uid=resource_value.getUid())
2501

2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
  def stepTestFullInventoryCollideWithEachOther(
        self, sequence=None, sequence_list=None, **kw):
    resource_value = sequence.get('resource')
    node_value = sequence.get('node')
    section_value = sequence.get('section')
    self._testGetInventory(expected=200,
                           section_uid=section_value.getUid(),
                           node_uid=node_value.getUid(),
                           resource_uid=resource_value.getUid())

  def stepTestInventoryCollisionByMovements(
        self, sequence=None, sequence_list=None, **kw):
    resource_value = sequence.get('resource')
    node_value = sequence.get('node')
    section_value = sequence.get('section')
    self._testGetInventory(expected=300,
                           section_uid=section_value.getUid(),
                           node_uid=node_value.getUid(),
                           resource_uid=resource_value.getUid())


  def stepTestInventoryCollisionByInventory(
        self, sequence=None, sequence_list=None, **kw):
    resource_value = sequence.get('resource')
    node_value = sequence.get('node')
    section_value = sequence.get('section')
    self._testGetInventory(expected=300,
                           section_uid=section_value.getUid(),
                           node_uid=node_value.getUid(),
                           resource_uid=resource_value.getUid())

2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
  def stepCreateTwoResourceFullInventory(self,
                                         sequence=None,
                                         sequence_list=None,
                                         **kw):
    """ Create a full Inventory which includes two inventory lines """
    inventory = self.createInventory(sequence=sequence)
    inventory_list = sequence.get('inventory_list',[])
    inventory.edit(full_inventory=True)
    inventory_line = inventory.newContent(
      portal_type = self.inventory_line_portal_type,
      resource_value = sequence.get("first_resource"),
      inventory = 10)
    inventory_line = inventory.newContent(
      portal_type = self.inventory_line_portal_type,
      resource_value = sequence.get("second_resource"),
      inventory = 100)
    inventory.deliver()
    inventory_list.append(inventory)
    sequence.edit(inventory_list=inventory_list)

  def stepCreateTwoResourceFullInventoryAtTheDate(self, sequence=None,
                                                  sequence_list=None, **kw):
    """ Create Full Inventory at the date' """
    inventory_list = sequence.get('inventory_list',[])
    if kw.get('start_date', None) is not None:
      start_date = kw['start_date']
    else:
      start_date = '2013/03/12 00:00:00 GMT+9'
    if kw.get('inventory1', None) is not None:
      inventory1 = kw['inventory1']
    else:
      inventory_1 = 10
    if kw.get('inventory2', None) is not None:
      inventory2 = kw['inventory2']
    else:
      inventory2 = 100

    inventory = self.createInventory(sequence=sequence)
    inventory_list = sequence.get('inventory_list',[])
    inventory.edit(full_inventory=True,
                   start_date=start_date)
    inventory_line = inventory.newContent(
      portal_type = self.inventory_line_portal_type,
      resource_value = sequence.get("resource"),
      inventory = inventory1)
    inventory_line = inventory.newContent(
      portal_type = self.inventory_line_portal_type,
      resource_value = sequence.get("second_resource"),
      inventory = inventory2)
    inventory.deliver()
    inventory_list.append(inventory)
    sequence.edit(inventory_list=inventory_list)

  def stepCreateTwoResourceFullInventoryAtTheDate1(self, sequence=None,
                                                   sequence_list=None, **kw):
    params = dict(start_date=self.two_resource_full_inventory1_start_date,
                  inventory1=self.two_resource_full_inventory1_inventory_1,
                  inventory2=self.two_resource_full_inventory1_inventory_2)
    self.stepCreateTwoResourceFullInventoryAtTheDate(sequence, sequence_list,
                                                     **params)

  def stepCreateTwoResourceFullInventoryAtTheDate2(self, sequence=None,
                                                   sequence_list=None, **kw):
    params = dict(start_date=self.two_resource_full_inventory2_start_date,
                  inventory1=self.two_resource_full_inventory2_inventory_1,
                  inventory2=self.two_resource_full_inventory2_inventory_2)
    self.stepCreateTwoResourceFullInventoryAtTheDate(sequence, sequence_list,
                                                     **params)

  def stepCheckFullInventoryUpdateWithValidDateOrder(
        self, sequence=None, sequence_list=None, **kw):
    resource_value = sequence.get('resource')
    second_resource_value = sequence.get('second_resource')
    node_value = sequence.get('node')
    section_value = sequence.get('section')
    self._testGetInventory(expected=100,
                           section_uid=section_value.getUid(),
                           node_uid=node_value.getUid(),
                           resource_uid=resource_value.getUid())
    self._testGetInventory(expected=0,
                           section_uid=section_value.getUid(),
                           node_uid=node_value.getUid(),
                           resource_uid=second_resource_value.getUid())
2616

2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
  def stepDubleStockValue(
        self, sequence=None, sequence_list=None, **kw):
    """
      Make stock table double
    """
    self.getPortalObject().erp5_sql_transactionless_connection.manage_test(
      "BEGIN\0"
      "UPDATE stock SET quantity=quantity*2 \0"
      "COMMIT")
    self.commit()

  def stepHalfStockValue(
        self, sequence=None, sequence_list=None, **kw):
    """
      Make stock table half
    """
    self.getPortalObject().erp5_sql_transactionless_connection.manage_test(
      "BEGIN\0"
      "UPDATE stock SET quantity=quantity/2 \0"
      "COMMIT")
    self.commit()


  def stepClearInventoryCache(
        self, sequence=None, sequence_list=None, **kw):
    """
      Explicitly Clear invenvory cache.
    """
    self.getPortalObject().erp5_sql_transactionless_connection.manage_test(
      "BEGIN\0"
      "DELETE FROM inventory_cache \0"
      "COMMIT")
    self.commit()


  def stepCheckCorruptedCacheHasFixedByReindex(
        self, sequence=None, sequence_list=None, **kw):
    """
      Make sure that corrupted caches are ignored when inventory document
      are reindexing.
    """
    resource_value = sequence.get('resource')
    node_value = sequence.get('node')
    section_value = sequence.get('section')
    self._testGetInventory(expected=100,
                           optimise=True,
                           to_date=DateTime(self.full_inventory_start_date_1),
                           section_uid=section_value.getUid(),
                           node_uid=node_value.getUid(),
                           resource_uid=resource_value.getUid())
    self._testGetInventory(expected=100,
                           optimise__=False,
                           to_date=DateTime(self.full_inventory_start_date_1),
                           section_uid=section_value.getUid(),
                           node_uid=node_value.getUid(),
                           resource_uid=resource_value.getUid())


  def stepStoreWrongCache(self, sequence=None, sequence_list=None, **kw):
    """
      Cache a corrupted stock data.
    """
    node_value = sequence.get('node')
    to_date=DateTime(self.two_resource_full_inventory2_start_date)
    self.getPortalObject().portal_simulation.getCurrentInventoryList(
      to_date=to_date,
      node=node_value.getRelativeUrl(),
      group_by_variation=1,
      group_by_sub_variation=1,
      group_by_resource=1)

2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
  def stepCheckGetInveotoryGoesToCache(
        self, sequence=None, sequence_list=None, **kw):
    """
      Get inventory then store the inventory_cache record
      thanks to the at_date parameter
    """
    resource_value = sequence.get('resource')
    second_resource_value = sequence.get('second_resource')
    node_value = sequence.get('node')
    section_value = sequence.get('section')
    at_date = DateTime('2013/06/11 00:00:00 GMT+9')
    self._testGetInventory(
      expected=15,
      section_uid=section_value.getUid(),
      node_uid=node_value.getUid(),
      resource_uid=resource_value.getUid(),
      at_date=at_date)
    self._testGetInventory(
      expected=20,
      section_uid=section_value.getUid(),
      node_uid=node_value.getUid(),
      resource_uid=second_resource_value.getUid(),
      at_date=at_date)

  def stepCheckInventoryCacheIsClearedAfterAddingInventory(
        self, sequence=None, sequence_list=None, **kw):
    """
      Check that older invetory_cache is cleared.
    """
    resource_value = sequence.get('resource')
    second_resource_value = sequence.get('second_resource')
    node_value = sequence.get('node')
    section_value = sequence.get('section')
    at_date = DateTime('2013/06/11 02:00:00 GMT+9')
    self._testGetInventory(
      expected=30,
      section_uid=section_value.getUid(),
      node_uid=node_value.getUid(),
      resource_uid=resource_value.getUid(),
      at_date=at_date)
    self._testGetInventory(
      expected=50,
      section_uid=section_value.getUid(),
      node_uid=node_value.getUid(),
      resource_uid=second_resource_value.getUid(),
      at_date=at_date)
2734

Guillaume Michon's avatar
Guillaume Michon committed
2735 2736
  def test_01_getInventory(self, quiet=0, run=run_all_test):
    """
2737
      Test the getInventory methods
Guillaume Michon's avatar
Guillaume Michon committed
2738 2739 2740 2741
    """
    if not run: return
    sequence_list = SequenceList()

2742 2743
    get_inventory_test_sequence= 'stepTestInventoryListBrainGetQuantity \
                                   stepTestGetInventoryOnNode \
Jérome Perrin's avatar
Jérome Perrin committed
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
                                   stepTestGetInventoryOnVariationCategory \
                                   stepTestGetInventoryOnPayment \
                                   stepTestGetInventoryOnSection \
                                   stepTestGetInventoryOnMirrorSection \
                                   stepTestGetInventoryOnResource \
                                   stepTestGetInventoryWithOmitInput \
                                   stepTestGetInventoryWithOmitOutput \
                                   stepTestGetInventoryOnSimulationState \
                                   stepTestGetInventoryOnSectionCategory \
                                   stepTestGetInventoryOnPaymentCategory \
                                   stepTestGetInventoryOnNodeCategory \
                                   stepTestGetInventoryOnMirrorSectionCategory \
                                   stepTestGetInventoryOnResourceCategory \
                                   stepTestGetInventoryOnVariationText \
2758 2759
                                   '
                                   #TestGetInventoryWithSelectionReport \
Jérome Perrin's avatar
Jérome Perrin committed
2760 2761 2762 2763 2764 2765
    get_inventory_test_sequence += 'stepTestGetInventoryListOnSection \
                                   stepTestGetInventoryListOnNode \
                                   stepTestGetInventoryListWithOmitInput \
                                   stepTestGetInventoryListWithOmitOutput \
                                   stepTestGetInventoryListWithGroupBy \
                                   stepTestGetNextNegativeInventoryDate \
2766
                                  '
Guillaume Michon's avatar
Guillaume Michon committed
2767

Jérome Perrin's avatar
Jérome Perrin committed
2768 2769 2770 2771 2772 2773 2774
    sequence_string = 'stepCreateOrganisationList \
                       stepCreateOrder \
                       stepCreateVariatedResourceList \
                       stepCreatePackingListList \
                       stepTic \
                       stepCreateTestingCategories \
                       stepTic \
2775
                       ' + get_inventory_test_sequence
Guillaume Michon's avatar
Guillaume Michon committed
2776 2777 2778 2779 2780
    sequence_list.addSequenceString(sequence_string)

    sequence_list.play(self)


2781 2782 2783 2784 2785 2786
  def test_02_InventoryModule(self, quiet=0, run=run_all_test):
    """
      Test the InventoryModule behavior
    """
    if not run: return
    sequence_list = SequenceList()
Guillaume Michon's avatar
Guillaume Michon committed
2787

Jérome Perrin's avatar
Jérome Perrin committed
2788 2789 2790 2791 2792
    sequence_string = 'stepCreateOrganisationsForModule \
                       stepCreateVariatedResource \
                       stepCreateItemList \
                       stepCreatePackingListForModule \
                       stepTic \
2793 2794 2795 2796
                       stepCreatePackingListLine \
                       stepTic \
                       stepDeliverPackingList \
                       stepTic \
Jérome Perrin's avatar
Jérome Perrin committed
2797 2798 2799 2800 2801 2802 2803 2804 2805
                       stepCreateAggregatingInventory \
                       stepTic \
                       stepTestInventoryModule \
                       stepCreateSingleInventory \
                       stepTic \
                       stepTestInventoryModule \
                       stepModifyFirstInventory \
                       stepTic \
                       stepTestInventoryModule \
2806 2807 2808 2809 2810
                       '
    sequence_list.addSequenceString(sequence_string)

    sequence_list.play(self)

2811
  def test_03_InventoryModuleWithVariation(self, quiet=0, run=run_all_test):
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
    """
      Test the InventoryModule behavior
    """
    if not run: return
    sequence_list = SequenceList()

    sequence_string = 'stepCreateOrganisationsForModule \
                       stepCreateVariatedResource \
                       stepTic \
                       stepCreatePackingListForModule \
                       stepTic \
                       stepCreateVariatedPackingListLine \
                       stepTic \
                       stepDeliverPackingList \
                       stepTic \
                       stepTestInitialVariatedInventory \
                       stepCreateSingleVariatedInventory \
                       stepTic \
                       stepTestVariatedInventoryAfterInventory \
                       '
    sequence_list.addSequenceString(sequence_string)

    sequence_list.play(self)

2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855
  def test_04_InventoryModuleWithVariationAndMultiQuantityUnit(self, quiet=0, run=run_all_test):
    """
      Test InventoryModule behavior with product which has
      variation and multiple quantity units.
    """
    if not run: return
    sequence_list = SequenceList()

    sequence_string = 'stepCreateOrganisationsForModule \
                       stepCreateVariatedMultipleQuantityUnitResource \
                       stepTic \
                       stepCreatePackingListForModule \
                       stepTic \
                       stepCreateVariatedNonDefaultQuantityUnitPackingListLine \
                       stepTic \
                       stepDeliverPackingList \
                       stepTic \
                       stepTestInitialVariatedNonDefaultQuantityUnitInventory \
                       stepCreateSingleVariatedInventory \
                       stepTic \
2856
                       stepTestVariatedInventoryNonDefaultQuantityUnitAfterInventory \
2857 2858 2859 2860
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
  def test_05_CancelInventoryAfterDelivered(self, quiet=0, run=run_all_test):
    """
      Make sure that changing workflow state after delivered changes
      records in stock table.
    """
    delivered_state = self.portal.portal_workflow.inventory_workflow.states['delivered']
    delivered_state.transitions = delivered_state.transitions + ('cancel',)

    self.commit()

    organisation = self.portal.organisation_module.newContent(portal_type='Organisation')
    product = self.portal.product_module.newContent(portal_type='Product')
    inventory = self.portal.inventory_module.newContent(portal_type='Inventory')
    inventory.edit(destination_value=organisation,
                   stop_date=DateTime('2012/09/12 00:00:00 GMT+9'))
    line = inventory.newContent(portal_type='Inventory Line')
    line.setResourceValue(product)
    line.setQuantity(100)

    self.tic()

    self.assertEqual(
      self.portal.portal_simulation.getCurrentInventory(
        node_uid=organisation.getUid(),
        resource_uid=product.getUid()),
      0)

    inventory.deliver()
    self.tic()

    self.assertEqual(
      self.portal.portal_simulation.getCurrentInventory(
        node_uid=organisation.getUid(),
        resource_uid=product.getUid()),
      100)

    inventory.cancel()
    self.tic()

    self.assertEqual(
      self.portal.portal_simulation.getCurrentInventory(
        node_uid=organisation.getUid(),
        resource_uid=product.getUid()),
      0)

2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981
  def test_06_FullInventory(self, quiet=0, run=run_all_test):
    """
      Test the full inventory behavior
    """
    if not run: return
    sequence_list = SequenceList()

    sequence_string = 'stepCreateOrganisationsForModule \
                       stepCreateNotVariatedResource \
                       stepCreateNotVariatedSecondResource \
                       stepCreateItemList \
                       stepCreatePackingListForModule \
                       stepTic \
                       stepCreatePackingListLine \
                       stepTic \
                       stepDeliverPackingList \
                       stepTic \
                       stepCreateFullInventory \
                       stepTic \
                       stepTestFullInventory \
                       '
    sequence_list.addSequenceString(sequence_string)

    sequence_list.play(self)

  def test_07_FullVariatedInventory(self, quiet=0, run=run_all_test):
    """
      Test the full inventory behavior with variated resource
    """
    if not run: return
    sequence_list = SequenceList()

    sequence_string = 'stepCreateOrganisationsForModule \
                       stepCreateVariatedResource \
                       stepCreateNotVariatedSecondResource \
                       stepCreateItemList \
                       stepCreatePackingListForModule \
                       stepTic \
                       stepCreateVariatedPackingListLine \
                       stepTic \
                       stepDeliverPackingList \
                       stepTic \
                       stepCreateFullVariatedInventory \
                       stepTic \
                       stepTestFullVariatedInventory \
                       '
    sequence_list.addSequenceString(sequence_string)

    sequence_list.play(self)

  def test_08_PartialInventoryMultipleResource(self, quiet=0, run=run_all_test):
    """
      Test behaviour of partial inventory with multiple resource
      defining inventory of resource B must not modify inventory of resource A
    """
    if not run: return
    sequence_list = SequenceList()

    sequence_string = 'stepCreateOrganisationsForModule \
                       stepCreateNotVariatedResource \
                       stepCreateNotVariatedSecondResource \
                       stepCreateItemList \
                       stepCreatePackingListForModule \
                       stepTic \
                       stepCreatePackingListLine \
                       stepTic \
                       stepDeliverPackingList \
                       stepTic \
                       stepCreatePartialInventoryMultipleResource \
                       stepTic \
                       stepTestPartialInventoryMultipleResource \
                       '
    sequence_list.addSequenceString(sequence_string)

    sequence_list.play(self)

2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015
  def test_09_FullInventoryWithResourceCategory(self, quiet=0, run=run_all_test):
    if not run: return
    sequence_list = SequenceList()

    sequence_string = 'CreateOrganisationsForModule \
                       SetTwoLevelProductLineOnFirstResource \
                       CreateNotVariatedSecondResource \
                       Tic \
                       CreateTwoResourceFullInventory \
                       Tic \
                       TestFullInventoryWithResourceCategory \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

  def test_09_FullInventoryWithSectionCategory(self, quiet=0, run=run_all_test):
    if not run: return
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       SetUpInventoryIndexingByNodeAndSection \
                       CreateNotVariatedSecondResource \
                       Tic \
                       CreateFullInventory \
                       Tic \
                       SetTwoLevelGroupOnSection \
                       Tic \
                       CreateFullInventory \
                       Tic \
                       TestFullInventoryWithSectionCategory \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

  def test_09_FullInventoryWithNodeCategory(self, quiet=0, run=run_all_test):
3016
    if not run: return
3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       SetUpInventoryIndexingByNodeAndSection \
                       CreateNotVariatedSecondResource \
                       Tic \
                       CreateFullInventory \
                       Tic \
                       SetTwoLevelRegionOnNode \
                       Tic \
                       CreateFullInventory \
                       Tic \
                       TestFullInventoryWithNodeCategory \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
  def test_10_MultipleSectionAndFullInventory(self, quiet=0, run=run_all_test):
    """Make sure that getInventory works in the situation which
    two sections use the same node and one section has full inventory for
    the node.
    For Example:
    movement: 2013/03/10, section=A, node=C, quantity=1
    movement: 2013/03/13, section=A, node=C, quantity=2
    movement: 2013/03/11, section=B, node=C, quantity=3
    movement: 2013/03/12, section=B, node=C, quantity=4

    full inventory: 2013/03/12, section=A, node=C, quantity=100

    getInventory(section_A_uid) should return 102 (not 103)
    getInventory(section_B_uid) should return 7 (not 100)
    """
    if not run: return
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       SetUpInventoryIndexingByNodeAndSection \
                       CreateNotVariatedResource \
                       Tic \
                       CreatePackingListForMultipleSectionAndFullInventory \
                       Tic \
                       DeliverAllPackingList \
                       Tic \
                       CreateFullInventoryAtTheDate \
                       Tic \
                       CheckMultipleSectionAndFullInventory \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)
3064

3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
  # Note: This inventory reindex function is not implemented yet
  @expectedFailure
  def test_11_FullInventoryAddOldMovement(self, quiet=0, run=run_all_test):
    """
    Make sure the following case:

    1) add movement 2013/02/10, quantity=100
    2) full inventory: 2013/03/15, quantity=100

    [test]
    getInventory() should return 100
    getMovementHistory() should return 100 ([100])

    3) add movement: 2013/02/01, quantity=100

    [test]
    getInventory() should return 100
    getMovementHistory() should return 100 ([-100, 100, 100])
    """
    if not run: return

3086
    self.full_inventory_start_date_1 = '2013/03/15 00:00:00 GMT+9'
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
    self.start_date_1 = '2013/02/10 00:00:00 GMT+9'
    self.start_date_2 = '2013/02/01 00:00:00 GMT+9'
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       CreateNotVariatedResource \
                       Tic \
                       CreatePackingListAtTheDate1 \
                       CreatePackingListLine \
                       Tic \
                       DeliverPackingList \
                       Tic \
                       CreateFullInventoryAtTheDate1 \
                       Tic \
                       CreatePackingListAtTheDate2 \
                       CreatePackingListLine \
                       Tic \
                       DeliverPackingList \
                       Tic \
                       CheckFullInventoryAddOldMovement \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)


3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150
  def test_12_UseBothFullAndPartialInventory(self, quiet=0, run=run_all_test):
    """
    Make sure a case Using both Full and Partial Inventories:

    The case is:
    1) inventory: 2013/01/10, section=A, node=B, resource=X, quantity=3
    2) full inventory: 2013/02/21,section=A, node=B, resource=Y, quantity=100
       (there is only *Y*. No X.)
    3) inventory: 2013/03/10,section=A, node=B, resource=X, quantity=3

    [test]
    getInventory(resource=X) should return 3
    getInventory(resource=X, optimise__=False) should return 3
    """
    if not run: return

    self.inventory_start_date_1 = '2013/01/10 00:00:00 GMT+9'
    self.full_inventory_start_date_1 = '2013/01/10 00:00:00 GMT+9'
    self.inventory_start_date_2 = '2013/03/10 00:00:00 GMT+9'
    self.full_inventory_resource_1 = 'resource'
    self.inventory_resource_1 = self.inventory_resource_2 = 'second_resource'
    self.inventory_1 = 3
    self.inventory_2 = 3
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       CreateNotVariatedResource \
                       CreateNotVariatedSecondResource \
                       Tic \
                       CreateInventoryAtTheDate1 \
                       Tic \
                       CreateFullInventoryAtTheDate1 \
                       Tic \
                       CreateInventoryAtTheDate2 \
                       Tic \
                       CheckUseBothFullAndPartialInventory \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)


3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
  def test_13_FullInventoryMultipleNodeAndResource(
        self, quiet=0, run=run_all_test):
    """
     Test a case that is using full inventory with multiple nodes and resources.

     The case:
     1) movement: section=A,node=B,resource=X,quantity=100
     2) movement: section=A,node=B,resource=Y,quantity=100
     3) full inventory: section=A,node=C,resource=Y,quantity=100

     [Test]
     getInventory(section=A, node=B, resource=X) should return 100
     getInventory(section=A, node=B, resource=Y) should return 100
     getInventory(section=A, node=C, resource=Y) should return 100
     getInventory(section=A, node=C, resource=X) should return 0
    """
    if not run: return

    self.start_date_1 = '2013/03/10 00:00:00 GMT+9'
    self.resource_1 = 'resource'
    self.start_date_2 = '2013/03/12 00:00:00 GMT+9'
    self.resource_2 = 'second_resource'
    self.full_inventory_start_date_1 = '2013/03/20 00:00:00 GMT+9'
    self.full_inventory_resource_1 = 'second_resource'
    self.full_inventory_node_1 = 'other_node'
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       SetUpInventoryIndexingByNodeAndSection \
                       CreateNotVariatedResource \
                       CreateNotVariatedSecondResource \
                       Tic \
                       CreatePackingListAtTheDate1 \
                       CreatePackingListLineWithResource1 \
                       Tic \
                       DeliverPackingList \
                       Tic \
                       CreatePackingListAtTheDate2 \
                       CreatePackingListLineWithResource2 \
                       Tic \
                       DeliverPackingList \
                       Tic \
                       CreateFullInventoryAtTheDate1 \
                       Tic \
                       TestFullInventoryMultipleNodeAndResource \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)


3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237
  def test_14_FullInventoryCollision(self, quiet=0, run=run_all_test):
    """
     Make sure a case when Full Inventory collide with other documents.

     The cases are:

     full inventory: 2013/03/20 00:00:00, section=A, node=B, quantity=100
     full inventory: 2013/03/20 00:00:00, section=A, node=B, quantity=100

     [Test]
     getInventory(section=A, node=B) should return 200 (not 100)

     movement: 2013/03/20 00:00:00, section=A, node=B, quantity=10
     movement: 2013/03/20 00:00:00, section=A, node=B, quantity=20
     full inventory: 2013/03/20 00:00:00, section=A, node=B, quantity=200

     [Test]
     getInventory(section=A, node=B) should return 230 (not 200)

     Full inventory acts as if it is created at FIRST among the SETS of the
     documents that are created at THE time.

     This is the specification of full inventory, the details are as follows.


     The specification when Full Inventory collide with others
     =========================================================

     case A [common usage]
     ---------------------

     1| packing list   | 2013/03/20 00:00:00 | 100
     2| packing list   | 2013/03/20 00:00:00 | 100
     3| full inventory | 2013/03/20 00:00:01 | 100 # The time is 00:00:01

     stock:
     1| movement | 2013/03/20 00:00:00 | 100
     2| movement | 2013/03/20 00:00:00 | 100
3238
     3| movement | 2013/03/20 00:00:01 | -100
3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400

     getInventory() should return 100

     This full inventory does not collide with others, it is a normal usage of
     full inventory.

     case B [less common usage]
     --------------------------

     1| full inventory | 2013/03/20 00:00:01 100
     2| packing list   | 2013/03/20 00:00:00 100
     3| packing list   | 2013/03/20 00:00:00 100

     stock:
     1| movement | 2013/03/20 00:00:01 | 100  # The time is 00:00:01 !
     2| movement | 2013/03/20 00:00:00 | 100
     3| movement | 2013/03/20 00:00:00 | 100

     getInventory() should return 100 (or should not be in this state)

     This behavior is OK in some business. Full inventory is created AS at last
     even if the creation_date is at first.
     Or, if you do not want to fall in this situation, you can reject such a
     packing list inputs with a proper Constraint.

     case C [collision by movements]
     -------------------------------

     Input documents:
     1| full inventory | 2013/03/20 00:00:00 | 100
     2| packing list   | 2013/03/20 00:00:00 | 100
     3| packing list   | 2013/03/20 00:00:00 | 100

     stock:
     1| movement | 2013/03/20 00:00:00 | 100
     2| movement | 2013/03/20 00:00:00 | 100
     3| movement | 2013/03/20 00:00:00 | 100

     getInventory() should return 300

     This behavior is probably natural, at the beginning of a day, someone
     create a full inventory, then users input daily movements.
     In such case, users' inputs should be respected.

     case D [collision by full inventory]
     ------------------------------------

     Input documents:
     1| packing list   | 2013/03/20 00:00:00 | 100
     2| packing list   | 2013/03/20 00:00:00 | 100
     3| full inventory | 2013/03/20 00:00:00 | 100

     stock:
     1| movement |  2013/03/20 00:00:00 | 100
     2| movement |  2013/03/20 00:00:00 | 100
     3| movement |  2013/03/20 00:00:00 | 100

     getInventory() returns 300? (or should not be in this state)

     This behavior probably sounds weird because even if the full inventory
     created at last within the same date, it does not reset stocks.
     In this case, proper constrains should reject the SAMEDATE-SAMETIME full
     inventory inputs.

     case E [full inventories collide with each other]
     -----------------------------------------

     Input documents:
     1|  full inventory | 2013/03/20 00:00:00 | 100
     1|  full inventory | 2013/03/20 00:00:00 | 100

     stock:
     1| movement |  2013/03/20 00:00:00 | 100
     2| movement |  2013/03/20 00:00:00 | 100

     getInventory() returns 200??

     This must be an unnatural behavior, in reality, production environments
     must not fall into this state, because both two full inventory argue that
     "I am the full inventory" in the same time. In such case, which should be
     the TRUE full inventory? How can you decide it? We can not answer it.

     In other words, this behavior is UNDEFINED, like x/0 in arithmetics.
     Thus appropriate constraints MUST reject those full inventory inputs.
    """
    if not run: return

    # case A and B are tested in other tests

    # case C [collision by movements]
    self.full_inventory_start_date_1 = '2013/03/20 00:00:00 GMT+9'
    self.full_inventory_resource_1 = 'resource'
    self.start_date_1 = '2013/03/20 00:00:00 GMT+9'
    self.resource_1 = 'resource'
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       SetUpInventoryIndexingByNodeAndSection \
                       CreateNotVariatedResource \
                       Tic \
                       CreateFullInventoryAtTheDate1 \
                       Tic \
                       CreatePackingListAtTheDate1 \
                       CreatePackingListLineWithResource1 \
                       Tic \
                       DeliverPackingList \
                       Tic \
                       CreatePackingListAtTheDate1 \
                       CreatePackingListLineWithResource1 \
                       Tic \
                       DeliverPackingList \
                       Tic \
                       TestInventoryCollisionByMovements \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

    # case D [collision by full inventory]
    self.start_date_1 = '2013/03/20 00:00:00 GMT+9'
    self.resource_1 = 'resource'
    self.full_inventory_start_date_1 = '2013/03/20 00:00:00 GMT+9'
    self.full_inventory_resource_1 = 'resource'
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       SetUpInventoryIndexingByNodeAndSection \
                       CreateNotVariatedResource \
                       Tic \
                       CreatePackingListAtTheDate1 \
                       CreatePackingListLineWithResource1 \
                       Tic \
                       DeliverPackingList \
                       Tic \
                       CreatePackingListAtTheDate1 \
                       CreatePackingListLineWithResource1 \
                       Tic \
                       DeliverPackingList \
                       Tic \
                       CreateFullInventoryAtTheDate1 \
                       Tic \
                       TestInventoryCollisionByInventory \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

    # case E [full inventories collide with each other]
    self.full_inventory_start_date_1 = '2013/03/20 00:00:00 GMT+9'
    self.full_inventory_resource_1 = 'resource'
    self.full_inventory_start_date_2 = '2013/03/20 00:00:00 GMT+9'
    self.full_inventory_resource_2 = 'resource'
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       SetUpInventoryIndexingByNodeAndSection \
                       CreateNotVariatedResource \
                       Tic \
                       CreateFullInventoryAtTheDate1 \
                       Tic \
                       CreateFullInventoryAtTheDate2 \
                       Tic \
                       TestFullInventoryCollideWithEachOther \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

3401 3402 3403 3404 3405
  def test_15_FullInventoryCanCreatesManyVirtualCompensationMovement(self, quiet=0, run=run_all_test):
    organisation = self.portal.organisation_module.newContent(portal_type='Organisation')
    resource_value_list = []
    for i in range(2000):
      resource_value_list.append(self.portal.product_module.newContent(portal_type='Product'))
3406

3407 3408
    self.commit()
    self.tic()
3409

3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463
    # Create initial inventory
    date_1 = DateTime('2013/04/29 00:00:00 GMT+9')
    result = self.portal.portal_simulation.getCurrentInventoryList(at_date=date_1,
                                                                   section_uid=organisation.getUid(),
                                                                   node_uid=organisation.getUid(),
                                                                   group_by_resource=1)
    self.assertEqual(len(result), 0)

    full_inventory_1 = self.portal.inventory_module.newContent(portal_type='Inventory')
    full_inventory_1.edit(destination_section_value=organisation,
                          destination_value=organisation,
                          start_date=date_1,
                          full_inventory=True)
    for resource_value in resource_value_list:
      full_inventory_1.newContent(portal_type='Inventory Line',
                                  resource_value=resource_value,
                                  quantity=123)
    full_inventory_1.deliver()

    self.commit()
    self.tic()

    result = self.portal.portal_simulation.getCurrentInventoryList(at_date=date_1,
                                                                   section_uid=organisation.getUid(),
                                                                   node_uid=organisation.getUid(),
                                                                   group_by_resource=1)
    self.assertEqual(sorted([(brain.resource_uid, brain.inventory)
                             for brain in result]),
                     sorted([(movement.getResourceUid(), movement.getQuantity())
                             for movement in full_inventory_1.getMovementList()]))

    # Create second inventory which deletes inventories of many resources.
    date_2 = DateTime('2013/05/03 00:00:00 GMT+9')
    full_inventory_2 = self.portal.inventory_module.newContent(portal_type='Inventory')
    full_inventory_2.edit(destination_section_value=organisation,
                          destination_value=organisation,
                          start_date=date_2,
                          full_inventory=True)
    full_inventory_2.newContent(portal_type='Inventory Line',
                                resource_value=resource_value_list[0],
                                quantity=1)
    full_inventory_2.deliver()

    self.commit()
    self.tic()

    result = self.portal.portal_simulation.getCurrentInventoryList(at_date=date_2,
                                                                   section_uid=organisation.getUid(),
                                                                   node_uid=organisation.getUid(),
                                                                   group_by_resource=1)
    self.assertEqual(sorted([(brain.resource_uid, brain.inventory)
                             for brain in result if brain.inventory != 0]),
                     sorted([(movement.getResourceUid(), movement.getQuantity())
                             for movement in full_inventory_2.getMovementList()]))
3464

3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
  @expectedFailure
  def test_16_CorruptedInventoryCacheAndFullInventory(
        self, quiet=0, run=run_all_test):
    """
    XXX-Tatuya: Do we really need to support this case?

    To make assure this validity, we must ignore all the cache when reindexing.

    Proof: Inventory caching caches more than one month older inventory,
    to make THIS inventory valid, we need to invalidate one month ago
    inventory's cache, and the one month ago inventory may wrongly cached two
    month ago inventory and.. by mathematical induction, we need to invalidate
    all the cache when getting inventory from new to old.
     In contrast, reindex from the oldest inventory up to the newest one must
    work if and only if..
    ALL THE WRONG CACHES CAN BE REMOBED/IGNORED BY INVENTORY DOCUMENTS REINDEX.
     For example, if the oldest wrong cache date is 31 days before than the
    oldest inventory, re-index and stock table will be corrupted.
     The cache is still enable because it is older than 30 days ago and newer
    than 60 days ago, at the same time it can not be remobed because the date
    is older than the oldest inventory start_date.
    Thus we must ignore all the cache to make assure this case validity.

    The case is:
    1) full inventory: 2013/01/01,section=A, node=B, resource=X, quantity=100
                                                     resource=Y, quantity=100
    2) clear the existing cache
    3) modify stock table by hand
    4) cache the wrong stock result at 2013/02/02
       Note: Here we need to use between 2013/02/02 and 2013/02/28 to cache
             2013/01/01 stock data.
    5) fix back the stock table
    6) full inventory: 2013/02/02,section=A, node=B, resource=X, quantity=100
                                                     resource=Y, quantity=100
       Note: Here we need to use between 2013/02/02 and 2013/02/28
    [test]
    getInventory(resource=X, to_date=2013/02/10) should return 100
    getInventory(resource=Y, to_date=2013/02/10) should return 100
    """
    if not run: return
    self.two_resource_full_inventory1_start_date = '2013/01/01 00:00:00 GMT+9'
    self.two_resource_full_inventory1_inventory_1 = 100
    self.two_resource_full_inventory1_inventory_2 = 100
    self.two_resource_full_inventory2_start_date = '2013/02/02 00:00:00 GMT+9'
    self.two_resource_full_inventory2_inventory_1 = 100
    self.two_resource_full_inventory2_inventory_2 = 100
    self.full_inventory_start_date_1 = '2013/02/10 00:00:00 GMT+9'
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       CreateNotVariatedResource \
                       CreateNotVariatedSecondResource \
                       CreateTwoResourceFullInventoryAtTheDate1 \
                       Tic \
                       ClearInventoryCache \
                       DubleStockValue \
                       StoreWrongCache \
                       HalfStockValue \
                       CreateTwoResourceFullInventoryAtTheDate2 \
                       Tic \
                       CheckCorruptedCacheHasFixedByReindex \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569
  def test_17_FullInventoryUpdateWithValidDateOrder(
        self, quiet=0, run=run_all_test):
    """
    Confirm Full inventory update with a valid start_date order

    The case is:
    1) full inventory: 2013/02/01,section=A, node=B, resource=X, quantity=15
                                                     resource=Y, quantity=20
    2) full inventory: 2013/02/02,section=A, node=B, resource=X, quantity=20
                                                     resource=Y, quantity=50
    3) full inventory: 2013/02/10,section=A, node=B, resource=X, quantity=100
        -> X:100
           Y:0  # creates a dummy movement with quantity=-50
    [test]
    getInventory(resource=X, to_date=2013/02/15) should return 100
    getInventory(resource=Y, to_date=2013/02/15) should return 0
    """
    if not run: return

    self.two_resource_full_inventory1_start_date = '2013/02/01 00:00:00 GMT+9'
    self.two_resource_full_inventory1_inventory_1 = 15
    self.two_resource_full_inventory1_inventory_2 = 20
    self.two_resource_full_inventory2_start_date = '2013/02/02 00:00:00 GMT+9'
    self.two_resource_full_inventory2_inventory_1 = 20
    self.two_resource_full_inventory2_inventory_2 = 50
    self.full_inventory_start_date_1 = '2013/02/10 00:00:00 GMT+9'
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       CreateNotVariatedResource \
                       CreateNotVariatedSecondResource \
                       CreateTwoResourceFullInventoryAtTheDate1 \
                       Tic \
                       CreateTwoResourceFullInventoryAtTheDate2 \
                       Tic \
                       CreateFullInventoryAtTheDate1 \
                       Tic \
                       CheckFullInventoryUpdateWithValidDateOrder \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
  def test_18_InventoryDocumentAndInventoryCache(
        self, quiet=0, run=run_all_test):
    """
    Check that inventory caches that are older than inventory stock movements
    are cleared.

    The case is:
    1) full inventory: 2013/05/01,section=A, node=B, resource=X, quantity=15
                                                     resource=Y, quantity=20
    [test]
    2) getInventory(section=A, node=B, resource=X, at_date=2013/06/11 00:00)
         => should return 15
       getInventory(section=A, node=B, resource=Y, at_date=2013/06/11 00:00)
         => should return 20

    3) full inventory: 2013/05/02,section=A, node=B, resource=X, quantity=30
                                                     resource=Y, quantity=50

    [test]
    4) getInventory(section=A, node=B, resource=X, at_date=2013/06/11 02:00)
       => should return 30
    4) getInventory(section=A, node=B, resource=Y, at_date=2013/06/11 02:00)
       => should return 50
    """
    if not run: return

    self.two_resource_full_inventory1_start_date = '2013/05/01 00:00:00 GMT+9'
    self.two_resource_full_inventory1_inventory_1 = 15
    self.two_resource_full_inventory1_inventory_2 = 20
    self.two_resource_full_inventory2_start_date = '2013/05/02 00:00:00 GMT+9'
    self.two_resource_full_inventory2_inventory_1 = 30
    self.two_resource_full_inventory2_inventory_2 = 50
    sequence_list = SequenceList()
    sequence_string = 'CreateOrganisationsForModule \
                       CreateNotVariatedResource \
                       CreateNotVariatedSecondResource \
                       CreateTwoResourceFullInventoryAtTheDate1 \
                       Tic \
                       CheckGetInveotoryGoesToCache \
                       CreateTwoResourceFullInventoryAtTheDate2 \
                       Tic \
                       CheckInventoryCacheIsClearedAfterAddingInventory \
                       '
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

3616

3617 3618 3619 3620
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestInventory))
  return suite