testSimulationPerformance.py 35 KB
Newer Older
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
##############################################################################
#
# Copyright (c) 2010 Nexedi SA and Contributors. All Rights Reserved.
#          Yoshinori Okuji <yo@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################

r"""Performance tests for simulation.

The purpose of these tests is to measure the performance of the following
basic operations in simulation:

  - the creation of new Applied Rules and the expansion of simulation
  - the expansion of simulation from existing Applied Rules
  - the expansion of simulation which results in convergence
  - the expansion of simulation which results in divergence
  - the adoption of previsions by a Target Solver
  - the acceptance of decisions by a Target Solver
  - the creation of new Applied Rules from partially simulated documents
  - the creation of new Deliveries by Delivery Builders
  - the addition of new Movements into existing Deliveries by Delivery Builders

For the testing environment, these document types are used for Deliveries:

  - Sale Order
  - Sale Packing List
  - Sale Invoice

Since Sale Invoices consist of Movements generated from Sale Packing Lists,
and Movements generated by Trade Model Lines, the simulation trees consist
of at most 4 levels in this order:

  - Order Simulation Rule
  - Packing List Simulation Rule
  - Invoice Simulation Rule
  - Trade Model Simulation Rule

In order to simulate various patterns of building, the following rules
are defined:

  - Sale Order is completed at "ordered"
  - Sale Packing List is completed at "stopped"
  - Sale Packing Lists are grouped by destination and by Sale Order
  - Sale Invoices are not

So, the relationship between Sale Order and Sale Packing List is 1:N,
and that between Sale Packing List and Sale Invoice is M:N.

"""

import unittest
from time import time
import gc
import subprocess
76
import hotshot
77 78 79 80 81 82 83 84 85 86

import transaction
from DateTime import DateTime
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from zLOG import LOG
from Products.ERP5Type.tests.utils import LogInterceptor
from Products.ERP5Type.tests.Sequence import SequenceList

# Define variable to chek if performance are good or not
# XXX These variable are specific to the testing environment
87
#     (pystone results: min: < 75757.6 - mean: ~ 77174.4 - max: > 78125)
88 89 90 91 92
# Historical values are here to remember original values on this
# specific testing environment. We must always try to stay below max
# historical values.

EXPECTED_MIN_MAX_TIME = {
93
  'Creation Of New Applied Rules': (34.8, 36.8),
94

95
  'Expansion of Existing Applied Rules': (16.9, 19.5),
96

97
  'Creation of New Sale Packing Lists': (37.4, 38.9),
98

99
  'Expansion of Converged Changes': (22.0, 24.8),
100

101
  'Expansion of Diverged Changes': (24.6, 26.9),
102

103
  'Adoption of Previsions': (17.9, 18.7),
104

105
  'Acceptance of Decisions': (14.5, 15.2),
106

107
  'Creation of New Applied Rules from Partially Simulated Deliveries':
108
    (51.2, 52.8),
109

110
  'Creation Of New Sale Invoices': (90.0, 98.5),
111

112
  'Addition of New Invoices Lines': (145.1, 157.6),
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
}

class TestSimulationPerformance(ERP5TypeTestCase, LogInterceptor):

    def getTitle(self):
      return "Simulation Performance"

    def getBusinessTemplateList(self):
      """
        Return the list of business templates.
      """
      return ('erp5_base',
              'erp5_pdm',
              'erp5_trade', 
              'erp5_invoicing',
              'erp5_accounting',
              'erp5_advanced_invoicing',
              'erp5_simulation_performance_test',)

    def afterSetUp(self):
      """
        Executed before each test_*.
      """
      self.login()
      portal = self.getPortal()

      # Validate some documents.
      for rule in portal.portal_rules.objectValues():
        if rule.getValidationState() != 'validated' \
                and rule.getId().startswith('test_'):
          rule.validate()

      for trade_condition in portal.sale_trade_condition_module.objectValues():
        if trade_condition.getValidationState() != 'validated':
          trade_condition.validate()

      for business_process in portal.business_process_module.objectValues():
        if business_process.getValidationState() != 'validated':
          business_process.validate()

      subprocess.call('sync')
154
      #self.prof = hotshot.Profile('hoge.prof')
155 156

    def beforeTearDown(self):
157
      #self.prof.close()
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
      transaction.abort()
      portal = self.getPortal()
      for module_id in ('sale_order_module', 'sale_packing_list_module',
              'sale_invoice_module', 'portal_simulation'):
        module = portal[module_id]
        module.manage_delObjects(list(module.objectIds()))
        transaction.commit()
        self.tic()

    def _getMinMaxTime(self, target):
      return EXPECTED_MIN_MAX_TIME[target]

    def _checkSimulation(self,
            number_of_sale_orders=None,
            number_of_sale_order_lines=None,
            number_of_additional_sale_packing_list_lines=None,
            measurable=True):
      sequence_string = """
              Initialize
              Tic
              UseClientAsDestinationDecision
              UseClientAsDestinationAdministration
              UseResourceAsCommodityProduct
              CreateSaleOrders
              Tic
              PlanSaleOrders
              MeasureCreationOfNewAppliedRules
              Tic
              CheckSaleOrderSimulation
              UseRecipient1AsDestinationDecision
              ModifySaleOrders
              MeasureExpansionOfExistingAppliedRules
              Tic
              CheckSaleOrderSimulation
              OrderSaleOrders
              MeasureCreationOfNewSalePackingLists
              Tic
              CheckSaleOrderSimulation
              CheckBuiltSalePackingLists
              UseRecipient2AsDestinationDecision
              ModifySaleOrders
              MeasureExpansionOfConvergedChanges
              Tic
              CheckSaleOrderSimulation
              CheckConvergedSalePackingLists
              UseRecipient1AsDestinationAdministration
              ModifySaleOrders
              MeasureExpansionOfDivergedChanges
              Tic
              CheckSaleOrderSimulation
              CheckDivergedSalePackingLists
              SetSolverTargetToDestinationAdministration
              AdoptPrevisionToSalePackingLists
              MeasureAdoptionOfPrevisions
              Tic
              CheckConvergedSalePackingLists
              UseRecipient2AsDestinationAdministration
              ModifySaleOrders
              Tic
              CheckSaleOrderSimulation
              CheckDivergedSalePackingLists
              SetSolverTargetToDestinationAdministration
              AcceptDecisionOfSalePackingLists
              MeasureAcceptanceOfDecisions
              Tic
223
              UseRecipient1AsDestinationAdministration
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 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
              CheckConvergedSalePackingLists
              ConfirmSaleOrders
              Tic
              UseResourceAsCommodityProduct
              AddNewSalePackingLinesIntoSalePackingLists
              MeasureCreationOfNewAppliedRulesFromPartiallySimulatedDeliveries
              Tic
              CheckSalePackingListSimulation
              StopSalePackingLists
              MeasureCreationOfNewSaleInvoices
              Tic
              CheckBuiltSaleInvoices
              UseResourceAsLuxuryProduct
              AddNewSalePackingLinesIntoSalePackingLists
              DeliverSalePackingLists
              MeasureAdditionOfNewInvoiceLinesIntoSaleInvoices
              Tic
              CheckAddedSaleInvoices
              TestResult
              """

      sequence = SequenceList()

      self.assertTrue(isinstance(number_of_sale_orders, int))
      self.assertTrue(number_of_sale_orders > 0)

      self.assertTrue(isinstance(number_of_sale_order_lines, int))
      self.assertTrue(number_of_sale_order_lines > 0)

      self.assertTrue(isinstance(number_of_additional_sale_packing_list_lines,
                                 int))
      self.assertTrue(number_of_additional_sale_packing_list_lines > 0)

      self.assertTrue(measurable in (True, False))

      self._init_dict = dict(number_of_sale_orders=number_of_sale_orders,
              number_of_sale_order_lines=number_of_sale_order_lines,
              number_of_additional_sale_packing_list_lines=number_of_additional_sale_packing_list_lines,
              measurable=measurable)

      sequence.addSequenceString(sequence_string)
      sequence.play(self)

    def stepInitialize(self, sequence=None, sequence_list=None, **kw):
      sequence.edit(**self._init_dict)

    def stepTic(self, sequence=None, sequence_list=None, **kw):
      if sequence is None:
        transaction.commit()

      measurable = False
      if sequence is not None:
        target = sequence.get('measure_target')
        if target is not None:
          measurable = sequence.get('measurable')

      # Reduce noise effect.
      subprocess.call('sync')
      gc.collect()

      if measurable:
        before_time = time()

287
      #self.prof.start()
288
      self.tic()
289
      #self.prof.stop()
290 291 292 293

      if measurable:
        after_time = time()
        amount_of_time = after_time - before_time
294
        min_time, max_time = self._getMinMaxTime(target)
295
        print "\n%s took %.4f (%.4f < %.4f < %.4f)" \
296 297 298 299 300 301 302
                % (target, amount_of_time, min_time, amount_of_time, max_time)
        # Reset the target to make sure that the same target is not
        # measured again.
        sequence.edit(measure_target=None)
        # Set the result.
        result = sequence.get('result', [])
        result.append((target, min_time, amount_of_time, max_time))
303
        sequence.edit(result=result)
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337

    def stepMeasureCreationOfNewAppliedRules(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('measure_target', 'Creation Of New Applied Rules')

    def stepMeasureExpansionOfExistingAppliedRules(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('measure_target', 'Expansion of Existing Applied Rules')

    def stepMeasureCreationOfNewSalePackingLists(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('measure_target', 'Creation of New Sale Packing Lists')

    def stepMeasureExpansionOfConvergedChanges(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('measure_target', 'Expansion of Converged Changes')

    def stepMeasureExpansionOfDivergedChanges(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('measure_target', 'Expansion of Diverged Changes')

    def stepMeasureAdoptionOfPrevisions(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('measure_target', 'Adoption of Previsions')

    def stepMeasureAcceptanceOfDecisions(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('measure_target', 'Acceptance of Decisions')

    def stepMeasureCreationOfNewAppliedRulesFromPartiallySimulatedDeliveries(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('measure_target',
              'Creation of New Applied Rules from Partially Simulated Deliveries')

338
    def stepMeasureCreationOfNewSaleInvoices(self, sequence=None,
339 340 341
            sequence_list=None, **kw):
      sequence.set('measure_target', 'Creation Of New Sale Invoices')

342 343
    def stepMeasureAdditionOfNewInvoiceLinesIntoSaleInvoices(self,
            sequence=None, sequence_list=None, **kw):
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
      sequence.set('measure_target', 'Addition of New Invoices Lines')

    def stepUseClientAsDestinationDecision(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('destination_decision', 'organisation_module/client')

    def stepUseRecipient1AsDestinationDecision(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('destination_decision', 'organisation_module/recipient1')

    def stepUseRecipient2AsDestinationDecision(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('destination_decision', 'organisation_module/recipient2')

    def stepUseClientAsDestinationAdministration(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('destination_administration', 'organisation_module/client')

    def stepUseRecipient1AsDestinationAdministration(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('destination_administration',
              'organisation_module/recipient1')

367 368 369 370 371
    def stepUseRecipient2AsDestinationAdministration(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('destination_administration',
              'organisation_module/recipient2')

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 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 436 437 438
    def stepUseResourceAsCommodityProduct(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('resource', 'product_module/commodity')

    def stepUseResourceAsLuxuryProduct(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('resource', 'product_module/luxury')

    def stepCreateSaleOrders(self, sequence=None, sequence_list=None, **kw):
      portal = self.getPortal()
      module = portal.sale_order_module
      base_date = DateTime('2010-08-08')
      number_of_sale_orders = sequence.get('number_of_sale_orders')
      number_of_sale_order_lines = sequence.get('number_of_sale_order_lines')
      destination_decision = sequence.get('destination_decision')
      destination_administration = sequence.get('destination_administration')
      resource = sequence.get('resource')
      for i in xrange(number_of_sale_orders):
        start_date = base_date + i
        stop_date = base_date + i + 1
        order = module.newContent(
                portal_type='Sale Order',
                specialise='sale_trade_condition_module/test_stc',
                destination_decision=destination_decision,
                destination_administration=destination_administration,
                start_date=start_date,
                stop_date=stop_date)
        # Set the rest through the trade condition.
        order.SaleOrder_applySaleTradeCondition()
        for j in xrange(number_of_sale_order_lines):
          order.newContent(portal_type='Sale Order Line',
                  resource=resource, quantity=1.0)

    def stepModifySaleOrders(self, sequence=None, sequence_list=None, **kw):
      portal = self.getPortal()
      module = portal.sale_order_module
      destination_decision = sequence.get('destination_decision')
      destination_administration = sequence.get('destination_administration')
      for order in module.contentValues(portal_type='Sale Order'):
        order.edit(destination_decision=destination_decision,
                destination_administration=destination_administration)
        self.assertEquals(order.getDestinationDecision(), destination_decision)
        self.assertEquals(order.getDestinationAdministration(),
                destination_administration)

    def stepPlanSaleOrders(self, sequence=None, sequence_list=None, **kw):
      portal = self.getPortal()
      module = portal.sale_order_module
      for order in module.contentValues(portal_type='Sale Order'):
        self.assertEquals(order.getSimulationState(), 'draft')
        order.plan()
        self.assertEquals(order.getSimulationState(), 'planned')

    def stepOrderSaleOrders(self, sequence=None, sequence_list=None, **kw):
      portal = self.getPortal()
      module = portal.sale_order_module
      for order in module.contentValues(portal_type='Sale Order'):
        self.assertEquals(order.getSimulationState(), 'planned')
        order.order()
        self.assertEquals(order.getSimulationState(), 'ordered')

    def stepConfirmSaleOrders(self, sequence=None, sequence_list=None, **kw):
      portal = self.getPortal()
      module = portal.sale_order_module
      for order in module.contentValues(portal_type='Sale Order'):
        self.assertEquals(order.getSimulationState(), 'ordered')
        order.confirm()
439
        self.assertEquals(order.getSimulationState(), 'confirmed')
440 441 442 443 444 445 446 447 448 449 450 451

    def stepCheckSaleOrderSimulation(self, sequence=None, sequence_list=None,
            **kw):
      portal = self.getPortal()
      module = portal.sale_order_module
      number_of_sale_orders = sequence.get('number_of_sale_orders')
      number_of_sale_order_lines = sequence.get('number_of_sale_order_lines')
      destination_decision = sequence.get('destination_decision')
      destination_administration = sequence.get('destination_administration')
      resource = sequence.get('resource')
      self.assertEquals(module.objectCount(), number_of_sale_orders)
      for order in module.contentValues(portal_type='Sale Order'):
452
        causality_list = order.getCausalityRelatedValueList(portal_type='Applied Rule')
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
        self.assertEquals(len(causality_list), 1)
        applied_rule = causality_list[0]
        self.assertEquals(applied_rule.getPortalType(), 'Applied Rule')
        rule = applied_rule.getSpecialiseValue()
        self.assertNotEquals(rule, None)
        self.assertEquals(rule.getReference(),
                'test_order_root_simulation_rule')
        self.assertEquals(applied_rule.objectCount(),
                number_of_sale_order_lines)
        for simulation_movement in applied_rule.objectValues():
          self.assertEquals(simulation_movement.getPortalType(),
                  'Simulation Movement')
          self.assertEquals(simulation_movement.getQuantity(), 1.0)
          self.assertEquals(simulation_movement.getResource(), resource)
          self.assertEquals(simulation_movement.getCausality(),
                  'business_process_module/test_bp/order')
          self.assertEquals(simulation_movement.getDestinationDecision(),
                  destination_decision)
          self.assertEquals(simulation_movement.getDestinationAdministration(),
                  destination_administration)

    def stepCheckBuiltSalePackingLists(self, sequence=None, sequence_list=None,
            **kw):
      portal = self.getPortal()
      module = portal.sale_packing_list_module
      number_of_sale_orders = sequence.get('number_of_sale_orders')
      number_of_sale_order_lines = sequence.get('number_of_sale_order_lines')
      destination_decision = sequence.get('destination_decision')
      destination_administration = sequence.get('destination_administration')
      resource = sequence.get('resource')
      self.assertEquals(module.objectCount(), number_of_sale_orders)
      for packing_list in module.contentValues():
        self.assertEquals(packing_list.getSimulationState(), 'confirmed')
        self.assertEquals(packing_list.getCausalityState(), 'solved')
        self.assertEquals(packing_list.getDestinationDecision(),
                destination_decision)
        self.assertEquals(packing_list.getDestinationAdministration(),
                destination_administration)
        self.assertEquals(packing_list.objectCount(), 1)
        for line in packing_list.objectValues():
          self.assertEquals(line.getResource(), resource)
          self.assertAlmostEquals(line.getQuantity(),
                  1.0 * number_of_sale_order_lines)
          simulation_movement_list = line.getDeliveryRelatedValueList()
497 498 499 500 501 502 503
          self.assertEquals(len(simulation_movement_list),
                  number_of_sale_order_lines)
          for simulation_movement in simulation_movement_list:
            self.assertEquals(simulation_movement.getPortalType(),
                    'Simulation Movement')
            self.assertEquals(simulation_movement.getCausality(),
                    'business_process_module/test_bp/shipping')
504 505 506 507 508 509 510 511 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

    def stepCheckBuiltSaleInvoices(self, sequence=None, sequence_list=None,
            **kw):
      portal = self.getPortal()
      module = portal.sale_invoice_module
      self.assertEquals(module.objectCount(), 1)
      number_of_sale_orders = sequence.get('number_of_sale_orders')
      number_of_sale_order_lines = sequence.get('number_of_sale_order_lines')
      number_of_additional_sale_packing_list_lines \
              = sequence.get('number_of_additional_sale_packing_list_lines')
      for invoice in module.contentValues():
        self.assertEquals(invoice.getSimulationState(), 'confirmed')
        self.assertEquals(invoice.getCausalityState(), 'solved')
        self.assertEquals(invoice.objectCount(), 2)
        invoice_line_list = invoice.objectValues(sort_on='resource')

        commodity_invoice_line = invoice_line_list[0]
        self.assertEquals(commodity_invoice_line.getResource(),
                'product_module/commodity')
        self.assertAlmostEquals(commodity_invoice_line.getQuantity(),
                1.0 * (number_of_sale_order_lines \
                        + number_of_additional_sale_packing_list_lines) \
                        * number_of_sale_orders)
        simulation_movement_list \
                = commodity_invoice_line.getDeliveryRelatedValueList()
        self.assertEquals(len(simulation_movement_list),
                (number_of_sale_order_lines \
                        + number_of_additional_sale_packing_list_lines) \
                        * number_of_sale_orders)
        for simulation_movement in simulation_movement_list:
          self.assertEquals(simulation_movement.getPortalType(),
                  'Simulation Movement')
          self.assertEquals(simulation_movement.getCausality(),
537
                  'business_process_module/test_bp/invoice')
538 539 540 541 542

        tax_invoice_line = invoice_line_list[1]
        self.assertEquals(tax_invoice_line.getResource(),
                'service_module/vat_low')
        self.assertAlmostEquals(tax_invoice_line.getQuantity(),
543 544 545
                commodity_invoice_line.getPrice() \
                        * (number_of_sale_order_lines \
                           + number_of_additional_sale_packing_list_lines) \
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
                        * number_of_sale_orders)
        simulation_movement_list \
                = tax_invoice_line.getDeliveryRelatedValueList()
        self.assertEquals(len(simulation_movement_list),
                (number_of_sale_order_lines \
                        + number_of_additional_sale_packing_list_lines) \
                        * number_of_sale_orders)
        for simulation_movement in simulation_movement_list:
          self.assertEquals(simulation_movement.getPortalType(),
                  'Simulation Movement')
          self.assertEquals(simulation_movement.getCausality(),
                  'business_process_module/test_bp/tax')

    def stepCheckAddedSaleInvoices(self, sequence=None, sequence_list=None,
            **kw):
      portal = self.getPortal()
      module = portal.sale_invoice_module
      self.assertEquals(module.objectCount(), 1)
      number_of_sale_orders = sequence.get('number_of_sale_orders')
      number_of_sale_order_lines = sequence.get('number_of_sale_order_lines')
      number_of_additional_sale_packing_list_lines \
              = sequence.get('number_of_additional_sale_packing_list_lines')
      for invoice in module.contentValues():
        self.assertEquals(invoice.getSimulationState(), 'confirmed')
        self.assertEquals(invoice.getCausalityState(), 'solved')
        self.assertEquals(invoice.objectCount(), 4)
        invoice_line_list = invoice.objectValues(sort_on='resource')

        commodity_invoice_line = invoice_line_list[0]
        self.assertEquals(commodity_invoice_line.getResource(),
                'product_module/commodity')
        self.assertAlmostEquals(commodity_invoice_line.getQuantity(),
                1.0 * (number_of_sale_order_lines \
                        + number_of_additional_sale_packing_list_lines) \
                        * number_of_sale_orders)
        simulation_movement_list \
                = commodity_invoice_line.getDeliveryRelatedValueList()
        self.assertEquals(len(simulation_movement_list),
                (number_of_sale_order_lines \
                        + number_of_additional_sale_packing_list_lines) \
                        * number_of_sale_orders)
        for simulation_movement in simulation_movement_list:
          self.assertEquals(simulation_movement.getPortalType(),
                  'Simulation Movement')
          self.assertEquals(simulation_movement.getCausality(),
591
                  'business_process_module/test_bp/invoice')
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607

        luxury_invoice_line = invoice_line_list[1]
        self.assertEquals(luxury_invoice_line.getResource(),
                'product_module/luxury')
        self.assertAlmostEquals(luxury_invoice_line.getQuantity(),
                1.0 * number_of_additional_sale_packing_list_lines \
                        * number_of_sale_orders)
        simulation_movement_list \
                = luxury_invoice_line.getDeliveryRelatedValueList()
        self.assertEquals(len(simulation_movement_list),
                number_of_additional_sale_packing_list_lines \
                        * number_of_sale_orders)
        for simulation_movement in simulation_movement_list:
          self.assertEquals(simulation_movement.getPortalType(),
                  'Simulation Movement')
          self.assertEquals(simulation_movement.getCausality(),
608
                  'business_process_module/test_bp/invoice')
609 610 611 612 613

        high_tax_invoice_line = invoice_line_list[2]
        self.assertEquals(high_tax_invoice_line.getResource(),
                'service_module/vat_high')
        self.assertAlmostEquals(high_tax_invoice_line.getQuantity(),
614 615
                luxury_invoice_line.getPrice() \
                        * number_of_additional_sale_packing_list_lines \
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
                        * number_of_sale_orders)
        simulation_movement_list \
                = high_tax_invoice_line.getDeliveryRelatedValueList()
        self.assertEquals(len(simulation_movement_list),
                number_of_additional_sale_packing_list_lines \
                        * number_of_sale_orders)
        for simulation_movement in simulation_movement_list:
          self.assertEquals(simulation_movement.getPortalType(),
                  'Simulation Movement')
          self.assertEquals(simulation_movement.getCausality(),
                  'business_process_module/test_bp/tax')

        low_tax_invoice_line = invoice_line_list[3]
        self.assertEquals(low_tax_invoice_line.getResource(),
                'service_module/vat_low')
        self.assertAlmostEquals(low_tax_invoice_line.getQuantity(),
632 633 634
                commodity_invoice_line.getPrice() \
                        * (number_of_sale_order_lines \
                           + number_of_additional_sale_packing_list_lines) \
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
                        * number_of_sale_orders)
        simulation_movement_list \
                = low_tax_invoice_line.getDeliveryRelatedValueList()
        self.assertEquals(len(simulation_movement_list),
                (number_of_sale_order_lines \
                        + number_of_additional_sale_packing_list_lines) \
                        * number_of_sale_orders)
        for simulation_movement in simulation_movement_list:
          self.assertEquals(simulation_movement.getPortalType(),
                  'Simulation Movement')
          self.assertEquals(simulation_movement.getCausality(),
                  'business_process_module/test_bp/tax')

    def stepCheckConvergedSalePackingLists(self, sequence=None,
            sequence_list=None, **kw):
      portal = self.getPortal()
      module = portal.sale_packing_list_module
      for packing_list in module.contentValues():
653
        self.assertEquals(packing_list.getCausalityState(), 'solved')
654 655 656 657 658 659

    def stepCheckDivergedSalePackingLists(self, sequence=None,
            sequence_list=None, **kw):
      portal = self.getPortal()
      module = portal.sale_packing_list_module
      for packing_list in module.contentValues():
660
        self.assertEquals(packing_list.getCausalityState(), 'diverged')
661 662 663 664 665 666 667 668 669 670 671

    def stepCheckSalePackingListSimulation(self, sequence=None,
            sequence_list=None, **kw):
      portal = self.getPortal()
      module = portal.sale_packing_list_module
      number_of_additional_sale_packing_list_lines \
              = sequence.get('number_of_additional_sale_packing_list_lines')
      destination_decision = sequence.get('destination_decision')
      destination_administration = sequence.get('destination_administration')
      for packing_list in module.contentValues(portal_type='Sale Packing List'):
        self.assertEquals(packing_list.getCausalityState(), 'solved')
672
        causality_list = packing_list.getCausalityRelatedValueList(portal_type='Applied Rule')
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
        self.assertEquals(len(causality_list), 1)
        applied_rule = causality_list[0]
        self.assertEquals(applied_rule.getPortalType(), 'Applied Rule')
        rule = applied_rule.getSpecialiseValue()
        self.assertNotEquals(rule, None)
        self.assertEquals(rule.getReference(),
                'test_packing_list_root_simulation_rule')
        self.assertEquals(applied_rule.objectCount(),
                number_of_additional_sale_packing_list_lines)
        for simulation_movement in applied_rule.objectValues():
          self.assertEquals(simulation_movement.getPortalType(),
                  'Simulation Movement')
          delivery_list = simulation_movement.getDeliveryValueList()
          self.assertEquals(len(delivery_list), 1)
          delivery = delivery_list[0]
          self.assertEquals(delivery.getPortalType(), 'Sale Packing List Line')
          self.assertEquals(simulation_movement.getQuantity(),
                  delivery.getQuantity())
          self.assertEquals(simulation_movement.getResource(),
                  delivery.getResource())
          self.assertEquals(simulation_movement.getCausality(),
                  'business_process_module/test_bp/shipping')
          self.assertEquals(simulation_movement.getDestinationDecision(),
                  destination_decision)
          self.assertEquals(simulation_movement.getDestinationAdministration(),
                  destination_administration)

    def stepSetSolverTargetToDestinationAdministration(self, sequence=None,
            sequence_list=None, **kw):
      sequence.set('solver_target', 'destination_administration')

    def stepAdoptPrevisionToSalePackingLists(self, sequence=None,
            sequence_list=None, **kw):
      solver_target = sequence.get('solver_target')
      self.assertTrue(isinstance(solver_target, str))
      portal = self.getPortal()
      module = portal.sale_packing_list_module
      for packing_list in module.contentValues(portal_type='Sale Packing List'):
        self.assertEquals(packing_list.getCausalityState(), 'diverged')
        packing_list.activate() \
                .SalePackingList_adoptPrevisionForTesting(solver_target)
      # Make sure that the same taget is not used again.
      sequence.edit(solver_target=None)

    def stepAcceptDecisionOfSalePackingLists(self, sequence=None,
            sequence_list=None, **kw):
      solver_target = sequence.get('solver_target')
      self.assertTrue(isinstance(solver_target, str))
      portal = self.getPortal()
      module = portal.sale_packing_list_module
      for packing_list in module.contentValues(portal_type='Sale Packing List'):
        self.assertEquals(packing_list.getCausalityState(), 'diverged')
        packing_list.activate() \
                .SalePackingList_acceptDecisionForTesting(solver_target)
      # Make sure that the same taget is not used again.
      sequence.edit(solver_target=None)

    def stepAddNewSalePackingLinesIntoSalePackingLists(self, sequence=None,
            sequence_list=None, **kw):
      portal = self.getPortal()
      module = portal.sale_packing_list_module
      number = sequence.get('number_of_additional_sale_packing_list_lines')
      resource = sequence.get('resource')
      for packing_list in module.contentValues(portal_type='Sale Packing List'):
        for i in xrange(number):
          packing_list.newContent(portal_type='Sale Packing List Line',
                  resource=resource, quantity=1.0)

    def stepStopSalePackingLists(self, sequence=None, sequence_list=None, **kw):
      portal = self.getPortal()
      module = portal.sale_packing_list_module
      for packing_list in module.contentValues(portal_type='Sale Packing List'):
        self.assertEquals(packing_list.getSimulationState(), 'confirmed')
        packing_list.stop()
        self.assertEquals(packing_list.getSimulationState(), 'stopped')

    def stepDeliverSalePackingLists(self, sequence=None, sequence_list=None,
            **kw):
      portal = self.getPortal()
      module = portal.sale_packing_list_module
      for packing_list in module.contentValues(portal_type='Sale Packing List'):
        self.assertEquals(packing_list.getSimulationState(), 'stopped')
755
        packing_list.deliver()
756 757 758 759 760 761 762
        self.assertEquals(packing_list.getSimulationState(), 'delivered')

    def stepTestResult(self, sequence=None, sequence_list=None, **kw):
      measurable = sequence.get('measurable')
      if measurable:
        result = sequence.get('result')
        if result:
763 764
          print ''
          failure_list = []
765
          for target, min_time, real_time, max_time in result:
766 767 768 769 770 771 772 773
            condition = (min_time < real_time < max_time)
            print '%s%s: %.4f < %.4f < %.4f' \
                    % (condition and ' ' or '!',
                            target, min_time, real_time, max_time)
            if not condition:
              failure_list.append(target)
          self.assertTrue(not failure_list,
                  'these tests failed: %s' % (', '.join(failure_list)))
774 775 776 777 778 779

    def test_01_CheckLogicAndMakeCacheHot(self):
      """Check the correctness of the logic as well as making the cache hot.
      """
      message = 'Check Logic'
      LOG('Testing... ', 0, message)
780
      #self.getPortal().portal_activities.manage_enableActivityTracking()
781 782 783 784
      self._checkSimulation(number_of_sale_orders=1,
              number_of_sale_order_lines=1,
              number_of_additional_sale_packing_list_lines=1,
              measurable=False)
785
      #self.getPortal().portal_activities.manage_disableActivityTracking()
786 787 788 789 790 791

    def test_02_CheckPerformance(self):
      """Check the performance.
      """
      message = 'Check Performance'
      LOG('Testing... ', 0, message)
792 793 794
      self._checkSimulation(number_of_sale_orders=5,
              number_of_sale_order_lines=5,
              number_of_additional_sale_packing_list_lines=5,
795 796 797 798 799 800
              measurable=True)

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