Package SimPy :: Module testSimPyTrace

[hide private]
[frames] | no frames]

# Source Code for Module SimPy.testSimPyTrace

       1  #!/usr / bin / env python
       2  # coding=utf-8
       3  from SimPy.MonitorTest import *
       4  from SimPy.SimulationTrace  import *
       5  import unittest
       6  from random import random
       7  # $Revision: 440 $ $Date: 2010-04-02 05:49:32 +0200 (Fri, 02 Apr 2010) $
       8  """testSimPyTraceOO.py
       9  SimPy version 2.1
      10  Unit tests for SimulationTrace.
      11
      12  #'$Revision: 440 $ $Date: 2010-04-02 05:49:32 +0200 (Fri, 02 Apr 2010) $ kgm'
      13
      14  """
      15  simulationTraceVersion=version
      16  print "Under test: SimulationTrace.py %s"%simulationTraceVersion
      17  __version__ = '2.1 $Revision: 440 $ $Date: 2010-04-02 05:49:32 +0200 (Fri, 02 Apr 2010) $ '
      18  print 'testSimPyTraceOO.py %s'%__version__
      19
      20  ## -------------------------------------------------------------
      21  ##                    TEST SIMULATION
      22  ## -------------------------------------------------------------
      23 -class P(Process):
      24     """ P class for testing"""
      25 -   def __init__(self, name = '', T = 0):
      26          Process.__init__(self)
      27          self.name = name
      28          self.T = T
      29
      30 -   def execute(self):
      31          yield hold, self, self.T
      32
      33 -class PActions(Process):
      34     """ PActions class for testing"""
      35 -   def __init__(self, name = '', T = 0):
      36          Process.__init__(self)
      37          self.name = name
      38          self.T = T
      39
      40 -   def ACTIONS(self):
      41          yield hold, self, self.T
      42
      43 -class ToStop(Process):
      44      """For testing stopSimulation
      45      """
      46 -    def run(self,stopTime):
      47          yield hold,self,now()+stopTime
      48          stopSimulation()
      49          yield hold,self,10
      50
      51 -class ToCollect(Process):
      52      """For testing startCollection
      53      """
      54 -    def run(self,mon1,mon2,tal1,tal2):
      55          while True:
      56              yield hold,self,1
      57              mon1.observe(now())
      58              mon2.observe(now())
      59              tal1.observe(now())
      60              tal2.observe(now())
      61
      62 -class ForEvtTimes(Process):
      63      """For testing allEventTimes
      64      """
      65 -    def run(self):
      66          yield hold,self
      67
      68 -class makeSimulationtestcase(unittest.TestCase):
      69     """ Tests of simulation
      70     """
      71 -   def testInit(self):
      72          """Test initialisation
      73          """
      74          initialize()
      75          simulate(until = 10)
      76          assert(now() == 0),'time not 0'
      77
      78 -   def testActivate(self):
      79          """Test activate()
      80          """
      81          P1 = P(name = 'P1', T = 100.0)
      82          initialize()
      83          activate(P1, P1.execute(),0)
      84          simulate(until = 5)
      85          assert(now() == 5),'Simulate stopped at %s not %s' % (now(),5)
      86
      87 -   def testStart(self):
      88         """Test start method
      89         """
      90         P1 = P(name = 'P1', T = 100.0)
      91         initialize()
      92         P1.start(P1.execute(),0)
      93         simulate(until = 5)
      94         assert(now() == 5),'Simulate stopped at %s not %s' % (now(),5)
      95
      96 -   def testStartActions(self):
      97        """Test start method with ACTIONS PEM
      98        """
      99        P1 = PActions(name = 'P1', T = 100.0)
     100        initialize()
     101        P1.start()
     102        simulate(until = 5)
     103        assert(now() == 5),'Simulate stopped at %s not %s' % (now(),5)
     104
     105 -   def testYield(self):
     106          """Test yield hold and simulate(until)
     107          """
     108          P1 = P(name = 'P1', T = 10)
     109          initialize()
     110          activate(P1, P1.execute(),0)
     111          simulate(until = 5)
     112          assert(now() == 5),'Simulate stopped at %s not %s' % (now(),5)
     113          ## should stop at 0 for next event is at 10s
     114          P2 = P(name = 'P2', T = 10)
     115          initialize()
     116          activate(P2, P2.execute(),0)
     117          simulate(until = 20)
     118          assert(now() == 10),'P1 hold to %s not %s' % (now(),10)
     119
     120
     121     ## ------------------------------------------------------------------------
     122     ## Tests of simulation utility functions/methods
     123     ## ------------------------------------------------------------------------
     124
     125 -   def testStopSimulation(self):
     126          """Test stopSimulation function/method
     127          """
     128          timeToStop = 7
     129          initialize()
     130          ts = ToStop()
     131          activate(ts,ts.run(stopTime = timeToStop))
     132          simulate(until = 50)
     133          assert(now()==timeToStop),\
     134          "stopSimulation not working; now = %s instead of %s"%(now(),timeToStop)
     135
     136 -   def testStartCollection(self):
     137         """Test startCollection function/method
     138         """
     139         initialize()
     140         tStart = 9
     141         mon1 = Monitor("mon1")
     142         mon2 = Monitor("mon2")
     143         tal1 = Tally("tal1")
     144         tal2 = Tally("tal2")
     145         startCollection(when = tStart,monitors=[mon1,mon2],tallies=[tal1,tal2])
     146         tc = ToCollect()
     147         activate(tc,tc.run(mon1,mon2,tal1,tal2))
     148         simulate(until=50)
     149         assert(mon1[0]==mon2[0]==[tStart,tStart]),\
     150                "startCollection not working correctly for Monitors"
     151         assert(tal1.count()==tal2.count()==50-tStart+1),\
     152                "startCollection not working for Tally"
     153
     154 -   def testAllEventTimes(self):
     155         """Test allEventTimes function/method
     156         """
     157         initialize()
     158         for i in range(3):
     159             f = ForEvtTimes()
     160             activate(f,f.run(),at=i)
     161         assert(allEventTimes()==[0,1,2]),\
     162                "allEventTimes not working"
     163
     164
     165
     166
     167 -def makeSSuite():
     168      suite = unittest.TestSuite()
     169      testInit = makeSimulationtestcase('testInit')
     170      testActivate = makeSimulationtestcase('testActivate')
     171      testStart = makeSimulationtestcase('testStart')
     172      testStartActions = makeSimulationtestcase('testStartActions')
     173      testYield = makeSimulationtestcase('testYield')
     174      testStopSimulation = makeSimulationtestcase('testStopSimulation')
     175      testStartCollection = makeSimulationtestcase('testStartCollection')
     176      testAllEventTimes = makeSimulationtestcase('testAllEventTimes')
     177      ##testrequest3 = makeSimulationtestcase('testrequest3')
     178      ##testrequest4 = makeSimulationtestcase('testrequest4')
     179      suite.addTests([testInit, testActivate, testStart, testStartActions,
     180                      testYield,testStopSimulation,testStartCollection,
     181                      testAllEventTimes])
     182      return suite
     183
     184  ## -------------------------------------------------------------
     185  ##                    TEST RESOURCES
     186  ## -------------------------------------------------------------
     187
     188 -class Job(Process):
     189     """ Job class for testing"""
     190 -   def __init__(self, server = None, name = ''):
     191          Process.__init__(self)
     192          self.name = name
     193          self.R = server
     194
     195 -   def execute(self):
     196          yield request, self, self.R
     197
     198
     199 -class makeResourcetestcase(unittest.TestCase):
     200     """ First simple tests of Resources
     201     """
     202 -   def testInit(self):
     203          """Test initialisation"""
     204          R = Resource()
     205          assert R.name == 'a_resource', 'Not null name'
     206          assert R.capacity == 1, 'Not unit capacity'
     207          assert R.unitName == 'units', 'Not the correct unit name'
     208          R = Resource(name = '', capacity = 1)
     209          assert R.name == '', 'Not null name'
     210          assert R.capacity == 1, 'Not unit capacity'
     211          assert R.unitName == 'units', 'Not the correct unit name'
     212          R = Resource(capacity = 3, name = '3 - version', unitName = 'blobs')
     213          assert R.name == '3 - version', 'Wrong name, it is' + R.name
     214          assert R.capacity == 3, 'Not capacity 3, it is '+`R.capacity`
     215          assert R.unitName == 'blobs', 'Not the correct unit name'
     216          ## next test 0 capacity is allowed
     217          R = Resource(capacity = 0, name = '0 - version')
     218          assert R.capacity == 0, 'Not capacity 0, it is '+`R.capacity`
     219
     220 -   def testrequest(self):
     221          """Test request"""
     222          ## NB this next call should be changed to
     223          ## R = Resource() when Simulation is fixed
     224          R0 = Resource(name = '', capacity = 0)
     225          assert R0.name == '', 'Not null name'
     226          assert R0.capacity == 0, 'Not capacity 0, it is ' + 'R0.capacity'
     227          ## now test requesting: ------------------------------------
     228          initialize()
     229          R1 = Resource(capacity = 0, name = '3 - version', unitName = 'blobs')
     230          J = Job(name = 'job', server = R1)
     231          activate(J, J.execute(), at = 0.0) # this requests a unit of R1
     232          ## when simulation starts
     233          simulate(until = 10.0)
     234          assert R1.n == 0, 'Should be 0, it is ' + str(R1.n)
     235          lenW = len(R1.waitQ)
     236          assert lenW == 1, 'Should be 1, it is ' + str(lenW)
     237          assert len(R1.activeQ) == 0, 'len activeQ Should be 0, it is '+\
     238          str(len(R1.activeQ))
     239
     240 -   def testrequest2(self):
     241          """Test request2 with capacity = 1"""
     242          ## now test requesting: ------------------------------------
     243          initialize()
     244          R2 = Resource(capacity = 1, name = '3 - version', unitName = 'blobs')
     245          J2 = Job(name = 'job', server = R2)
     246          activate(J2, J2.execute(), at = 0.0) # requests a unit of R2
     247          ## when simulation starts
     248          simulate(until = 10.0)
     249          assert R2.n == 0, 'Should be 0, it is ' + str(R2.n)
     250          lenW = len(R2.waitQ)
     251          lenA = len(R2.activeQ)
     252          assert lenW == 0, 'lenW Should be 0, it is ' + str(lenW)
     253          assert lenA == 1, 'lenA Should be 1, it is ' + str(lenA)
     254
     255 -   def testrequest3(self):
     256          """Test request3 with capacity = 1 several requests"""
     257          ## now test requesting: ------------------------------------
     258          initialize()
     259          R3 = Resource(capacity = 1, name = '3 - version', unitName = 'blobs')
     260          J2 = Job(name = 'job', server = R3)
     261          J3 = Job(name = 'job', server = R3)
     262          J4 = Job(name = 'job', server = R3)
     263          activate(J2, J2.execute(), at = 0.0) # requests a unit of R3
     264          activate(J3, J3.execute(), at = 0.0) # requests a unit of R3
     265          activate(J4, J4.execute(), at = 0.0) # requests a unit of R3
     266          ## when simulation starts
     267          simulate(until = 10.0)
     268          assert R3.n == 0, 'Should be 0, it is ' + str(R3.n)
     269          lenW = len(R3.waitQ)
     270          lenA = len(R3.activeQ)
     271          assert lenW == 2, 'lenW Should be 2, it is ' + str(lenW)
     272          assert R3.waitQ == [J3, J4],'WaitQ wrong' + str(R3.waitQ)
     273          assert lenA == 1, 'lenA Should be 1, it is ' + str(lenA)
     274          assert R3.activeQ == [J2],'activeQ wrong, it is ' + str(R3.activeQ[0])
     275
     276 -   def testrequest4(self):
     277          """Test request4 with capacity = 2 several requests"""
     278          ## now test requesting: ------------------------------------
     279          initialize()
     280          R3 = Resource(capacity = 2, name = '4 - version', unitName = 'blobs')
     281          J2 = Job(name = 'job', server = R3)
     282          J3 = Job(name = 'job', server = R3)
     283          J4 = Job(name = 'job', server = R3)
     284          activate(J2, J2.execute(), at = 0.0) # requests a unit of R3
     285          activate(J3, J3.execute(), at = 0.0) # requests a unit of R3
     286          activate(J4, J4.execute(), at = 0.0) # requests a unit of R3
     287          ## when simulation starts
     288          simulate(until = 10.0)
     289          assert R3.n == 0, 'Should be 0, it is ' + str(R3.n)
     290          lenW = len(R3.waitQ)
     291          lenA = len(R3.activeQ)
     292          assert lenW == 1, 'lenW Should be 1, it is ' + str(lenW)
     293          assert R3.waitQ == [J4],'WaitQ wrong' + str(R3.waitQ)
     294          assert lenA == 2, 'lenA Should be 2, it is ' + str(lenA)
     295          assert R3.activeQ == [J2, J3],'activeQ wrong, it is ' + str(R3.activeQ[0])
     296
     297  #------- Test Priority Queues
     298
     299 -   def testrequestPriority(self):
     300          """Test PriorityQ, with no preemption, 0 capacity"""
     301          class Job(Process):
     302             """ Job class for testing"""
     303             def __init__(self, server = None, name = ''):
     304                Process.__init__(self)
     305                self.name = name
     306                self.R = server
     307
     308             def execute(self, priority):
     309                yield request, self, self.R, priority
     310
     311          initialize()
     312          Rp = Resource(capacity = 0, qType = PriorityQ)
     313          J5 = Job(name = 'job 5', server = Rp)
     314          J6 = Job(name = 'job 6', server = Rp)
     315          J7 = Job(name = 'job 7', server = Rp)
     316          activate(J5, J5.execute(priority = 3))
     317          activate(J6, J6.execute(priority = 0))
     318          activate(J7, J7.execute(priority = 1))
     319          simulate(until = 100)
     320          assert Rp.waitQ == [J5, J7, J6],'WaitQ wrong' + str([(x.name, x.priority[Rp]) for x in Rp.waitQ])
     321
     322          """Test PriorityQ mechanism"""
     323
     324          def sorted(q):
     325             if not q or len(q) == 1:
     326                sortok = 1
     327                return sortok
     328             sortok = q[0] >= q[1] and sorted(q[2:])
     329             return sortok
     330
     331          initialize()
     332          Rp = Resource(capacity = 0, qType = PriorityQ)
     333          for i in range(10):
     334             J = Job(name = 'job ' + str(i),server = Rp)
     335             activate(J, J.execute(priority = random()))
     336          simulate(until = 1000)
     337          qp = [x._priority[Rp] for x in Rp.waitQ]
     338          assert sorted(qp),'waitQ not sorted by priority: ' + str([(x.name, x._priority[Rp]) for x in Rp.waitQ])
     339
     340
     341 -   def testrequestPriority1(self):
     342          """Test PriorityQ, with no preemption, capacity == 1"""
     343          class Job(Process):
     344             """ Job class for testing"""
     345             def __init__(self, server = None, name = ''):
     346                Process.__init__(self)
     347                self.name = name
     348                self.R = server
     349
     350             def execute(self, priority):
     351                yield request, self, self.R, priority
     352
     353          initialize()
     354          Rp = Resource(capacity = 1, qType = PriorityQ)
     355          J5 = Job(name = 'job 5', server = Rp)
     356          J6 = Job(name = 'job 6', server = Rp)
     357          J7 = Job(name = 'job 7', server = Rp)
     358          activate(J5, J5.execute(priority = 2))
     359          activate(J6, J6.execute(priority = 4))
     360          activate(J7, J7.execute(priority = 3))
     361          simulate(until = 100)
     362          assert Rp.waitQ == [J6, J7],'WaitQ wrong ' + str([(x.name, x._priority[Rp]) for x in Rp.waitQ])
     363
     364 -   def testrequestPriority2(self):
     365         """Test PriorityQ, with preemption, capacity == 1"""
     366         class nuJob(Process):
     367            def __init__(self, name):
     368               Process.__init__(self, name)
     369
     370            def execute(self, res, priority):
     371               self.preempt = len(res.activeQ) > 0 and priority > res.activeQ[-1]._priority[res]
     372               t = now()
     373               yield request, self, res, priority
     374               if self.preempt:
     375                  assert len(res.waitQ) == 1, 'No preemption ' + 'activeQ = ' + str(res.activeQ[0].name)
     376               yield hold, self, 30
     377               t1 = now()
     378               if self.preempt:
     379                  assert t + 30 == t1, 'Wrong completion time for preemptor ' + self.name
     380               else:
     381                  assert t + 60 == t1, 'Wrong completion time for preempted ' + self.name + ' ' + str(now())
     382               yield release, self, res
     383
     384         initialize()
     385         res = Resource(name = 'server', capacity = 1, qType = PriorityQ, preemptable = 1)
     386         n1 = nuJob(name = 'nuJob 1')
     387         n2 = nuJob(name = 'nuJob 2')
     388         activate(n1, n1.execute(res, priority = 0))
     389         activate(n2, n2.execute(res, priority = 1),at = 15)
     390         simulate(until = 100)
     391
     392 -   def testrequestPriority3(self):
     393         """Test preemption of preemptor"""
     394         class nuJob(Process):
     395            seqOut = []
     396            def __init__(self, name):
     397               Process.__init__(self, name)
     398               self.serviceTime = 30
     399
     400            def execute(self, res, priority):
     401               self.preempt = len(res.activeQ) > 0 and priority > res.activeQ[-1]._priority[res]
     402               nrwaiting = len(res.waitQ)
     403               yield request, self, res, priority
     404               if self.preempt:
     405                  assert len(res.waitQ) == nrwaiting + 1, 'No preemption ' + 'activeQ = ' + str(res.activeQ[0].name)
     406               yield hold, self, self.serviceTime
     407               yield release, self, res
     408               nuJob.seqOut.append((self, now()))
     409
     410         initialize()
     411         res = Resource(name = 'server', capacity = 1, qType = PriorityQ, preemptable = 1)
     412         n1 = nuJob(name = 'nuJob 1')
     413         n2 = nuJob(name = 'nuJob 2')
     414         n3 = nuJob(name = 'nuJob 3')
     415         activate(n1, n1.execute(res, priority=-1))
     416         start2 = 10
     417         activate(n2, n2.execute(res, priority = 0),at = start2)
     418         start3 = 20
     419         activate(n3, n3.execute(res, priority = 1),at = start3)
     420         simulate(until = 100)
     421         assert [x[1] for x in nuJob.seqOut] == [start3 + n3.serviceTime, start2 + 2 * n2.serviceTime, 90],\
     422                'Wrong service sequence / times: ' + str([x for x in nuJob.seqOut])
     423
     424 -   def testrequestNestedPreempt(self):
     425        """Test that a process can preempt another process holding multiple resources
     426        """
     427        class Requestor(Process):
     428            def run(self, res1, res2, res3, priority = 1):
     429                yield request, self, res1, priority
     430                yield request, self, res2, priority
     431                yield request, self, res3, priority
     432                record.observe(y = self.name)
     433                yield hold, self, 100
     434                record.observe(y = self.name)
     435                yield release, self, res3
     436                yield release, self, res2
     437                yield release, self, res1
     438
     439        initialize()
     440        outer = Resource(name = 'outer', qType = PriorityQ, preemptable = True)
     441        inner = Resource(name = 'inner', qType = PriorityQ, preemptable = True)
     442        innermost = Resource(name = 'innermost', qType = PriorityQ, preemptable = True)
     443        record = Monitor()
     444        r1 = Requestor('r1')
     445        activate(r1, r1.run(res1 = outer, res2 = inner, res3 = innermost, priority = 1))
     446        r2 = Requestor('r2')
     447        activate(r2, r2.run(res1 = outer, res2 = inner, res3 = innermost, priority = 10),at = 50)
     448        simulate(until = 200)
     449        assert record == [[0, 'r1'],[50, 'r2'],[150, 'r2'],[200, 'r1']],\
     450                'was %s; preempt did not work'%record
     451
     452
     453 -   def testmonitored(self):
     454        """ test monitoring of number in the two queues, waitQ and activeQ
     455        """
     456        class Job(Process):
     457            def __init__(self, name):
     458               Process.__init__(self, name)
     459
     460            def execute(self, res):
     461               yield request, self, res
     462               yield hold, self, 2
     463               yield release, self, res
     464
     465        initialize()
     466        res = Resource(name = 'server', capacity = 1, monitored = 1)
     467        n1 = Job(name = 'Job 1')
     468        n2 = Job(name = 'Job 2')
     469        n3 = Job(name = 'Job 3')
     470        activate(n1, n1.execute(res),at = 2)
     471        activate(n2, n2.execute(res),at = 2)
     472        activate(n3, n3.execute(res),at = 2) # 3 arrive at 2
     473        simulate(until = 100)
     474        assert res.waitMon == [[2, 1], [2, 2], [4, 1], [6, 0]],'Wrong waitMon:%s'%res.waitMon
     475        assert res.actMon == [[2, 1], [4, 0], [4, 1], [6, 0], [6, 1], [8, 0]],'Wrong actMon:%s'%res.actMon
     476        #print res.actMon
     477        assert res.waitMon.timeAverage() == (0 * 2 + 2 * 2 + 1 * 2) / 6.0, 'Wrong waitMon.timeAverage:%s'%res.waitMon.timeAverage()
     478
     479
     480 -def makeRSuite():
     481      suite = unittest.TestSuite()
     482      testInit = makeResourcetestcase('testInit')
     483      testrequest = makeResourcetestcase('testrequest')
     484      testrequest2 = makeResourcetestcase('testrequest2')
     485      testrequest3 = makeResourcetestcase('testrequest3')
     486      testrequest4 = makeResourcetestcase('testrequest4')
     487      testrequestPriority = makeResourcetestcase('testrequestPriority')
     488      testrequestPriority1 = makeResourcetestcase('testrequestPriority1')
     489      testrequestPriority2 = makeResourcetestcase('testrequestPriority2')
     490      testrequestPriority3 = makeResourcetestcase('testrequestPriority3')
     491      testrequestNestedPreempt = makeResourcetestcase('testrequestNestedPreempt')
     492      testmonitored = makeResourcetestcase('testmonitored')
     493      suite.addTests([testInit, testrequest, testrequest2, testrequest3, testrequest4, testrequestPriority,
     494                      testrequestPriority1, testrequestPriority2, testrequestPriority3,
     495                      testrequestNestedPreempt, testmonitored])
     496      return suite
     497
     498
     499  ##=====================================================
     500  ##                   Test Interrupts
     501  ##=====================================================
     502
     503
     504 -class Interruptor(Process):
     505 -   def __init__(self):
     506        Process.__init__(self)
     507
     508 -   def breakin(self, waitbefore, howoften = 1):
     509        for i in range(howoften):
     510           yield hold, self, waitbefore
     511           self.interrupt(victim)
     512
     513 -class Interrupted(Process):
     514 -   def __init__(self):
     515        Process.__init__(self)
     516
     517 -   def myActivity(self, howlong, theEnd = 200):
     518        global igothit
     519        igothit={}
     520        while now() <= theEnd:
     521           yield hold, self, howlong
     522           if self.interrupted():
     523              byWhom = self.interruptCause
     524              igothit[now()] = byWhom
     525           else:
     526              pass
     527
     528 -class makeInterrupttestcase(unittest.TestCase):
     529     """
     530     Tests interrupts as defined in SEP001v17
     531     """
     532 -   def testInterrupt1(self):
     533        """
     534        Test single interrupt during victim activity
     535        """
     536        global victim
     537        initialize()
     538        breaker = Interruptor()
     539        activate(breaker, breaker.breakin(10))
     540        victim = Interrupted()
     541        activate(victim, victim.myActivity(100))
     542        simulate(until = 200)
     543        assert igothit[10] == breaker, 'Not interrupted at 10 by breaker'
     544        assert len(igothit) == 1, 'Interrupted more than once'
     545
     546 -   def testInterrupt2(self):
     547        """
     548        Test multiple interrupts during victim activity
     549        """
     550        global victim
     551        initialize()
     552        breaker = Interruptor()
     553        activate(breaker, breaker.breakin(10, howoften = 3))
     554        victim = Interrupted()
     555        activate(victim, victim.myActivity(100))
     556        simulate(until = 200)
     557        for i in (10, 20, 30):
     558           assert igothit[i] == breaker, 'Not interrupted at %s by breaker' %i
     559        assert len(igothit) == 3, 'Interrupted wrong number of times'
     560
     561 -   def testInterrupt3(self):
     562        """
     563        Test interrupts after victim activity
     564        """
     565        global victim
     566        initialize()
     567        breaker = Interruptor()
     568        activate(breaker, breaker.breakin(50, howoften = 5))
     569        victim = Interrupted()
     570        activate(victim, victim.myActivity(10, theEnd = 10))
     571        simulate(until = 200)
     572        assert len(igothit) == 0, 'There has been an interrupt after victim lifetime'
     573
     574 -   def testInterrupt4(self):
     575        """
     576        Test multiple interrupts by multiple processes during victim activity
     577        """
     578        global victim
     579        initialize()
     580        breaker1 = Interruptor()
     581        activate(breaker1, breaker1.breakin(15, howoften = 3))
     582        breaker2 = Interruptor()
     583        activate(breaker2, breaker2.breakin(20, howoften = 3))
     584        victim = Interrupted()
     585        activate(victim, victim.myActivity(100))
     586        simulate(until = 200)
     587        for i in (15, 30, 45):
     588           assert igothit[i] == breaker1, 'Not interrupted at %s by breaker1' %i
     589        for i in (20, 40, 60):
     590           assert igothit[i] == breaker2, 'Not interrupted at %s by breaker2' %i
     591        assert len(igothit) == 6, 'Interrupted wrong number of times'
     592
     593 -   def testInterrupt5(self):
     594        """
     595        Test reset of 'interrupted' state.
     596        """
     597        global victim
     598        initialize()
     599        breaker = Interruptor()
     600        victim = Interrupted()
     601
     602        def newProcess(self):
     603           while True:
     604              assert not self.interrupted(),'Incorrectly interrupted'
     605              yield hold, self, 100
     606              if self.interrupted():
     607                 self.interruptReset()
     608                 assert not self.interrupted(),'Incorrectly interrupted'
     609
     610        victim.newProcess = newProcess
     611        activate(victim, newProcess(victim))
     612        activate(breaker, breaker.breakin(10, howoften = 3))
     613        simulate(until = 1000)
     614
     615 -def makeISuite():
     616     suite = unittest.TestSuite()
     617     testInterrupt1 = makeInterrupttestcase('testInterrupt1')
     618     testInterrupt2 = makeInterrupttestcase('testInterrupt2')
     619     testInterrupt3 = makeInterrupttestcase('testInterrupt3')
     620     testInterrupt4 = makeInterrupttestcase('testInterrupt4')
     621     testInterrupt5 = makeInterrupttestcase('testInterrupt5')
     622     suite.addTests([testInterrupt1, testInterrupt2, testInterrupt3, testInterrupt4, testInterrupt5])
     623     return suite
     624
     625  ## -------------------------------------------------------------
     626  ##                    TEST PROCESS STATES
     627  ## -------------------------------------------------------------
     628
     629 -class PS1(Process):
     630 -   def __init__(self):
     631        Process.__init__(self)
     632
     633 -   def life1(self):
     634        yield hold, self, 10
     635
     636 -   def life2(self):
     637        yield hold, self, 10
     638        yield passivate, self
     639        yield hold, self, 10
     640
     641 -class Observer1(Process):
     642 -   def __init__(self):
     643        Process.__init__(self)
     644
     645 -   def look1(self, p):
     646        assert p.active(),'p not active'
     647        assert not p.passive(), 'p passive'
     648        assert not p.terminated(),'p terminated'
     649        assert not p.interrupted(),'p interrupted'
     650        yield hold, self, 11
     651        assert not p.active(),'p active'
     652        assert not p.passive(),'p passive'
     653        assert p.terminated(),'p not terminated'
     654        assert not p.interrupted(),'p interrupted'
     655
     656 -   def look2(self, p):
     657        assert not p.active(),'p active'
     658        assert p.passive(),'p not passive'
     659        assert not p.terminated(),'p not terminated'
     660        assert not p.interrupted(),'p interrupted'
     661        activate(p, p.life1())
     662        yield hold, self, 11
     663        assert not p.active(),'p active'
     664        assert not p.passive(),'p not passive'
     665        assert p.terminated(),'p not terminated'
     666        assert not p.interrupted(),'p interrupted'
     667
     668 -   def look3(self, p):
     669        assert not p.active(),'p active'
     670        assert p.passive(),'p not passive'
     671        assert not p.terminated(),'p not terminated'
     672        assert not p.interrupted(),'p interrupted'
     673        activate(p, p.life2())
     674        yield hold, self, 11
     675        assert not p.active(),'p active'
     676        assert p.passive(),'p not passive'
     677        assert not p.terminated(),'p terminated'
     678        assert not p.interrupted(),'p interrupted'
     679
     680 -   def look4(self, p):
     681        yield hold, self, 5
     682        assert p.active(),'p not active'
     683        assert not p.passive(),'p passive'
     684        assert not p.terminated(),'p terminated'
     685        assert not p.interrupted(),'p interrupted'
     686        self.cancel(p)
     687        assert not p.active(),'p active'
     688        assert p.passive(),'p not passive'
     689        assert not p.terminated(),'p terminated'
     690        assert not p.interrupted(),'p interrupted'
     691        reactivate(p)
     692        assert p.active(),'p not active'
     693        assert not p.passive(),'p passive'
     694        assert not p.terminated(),'p terminated'
     695        assert not p.interrupted(),'p interrupted'
     696        yield hold, self
     697        assert not p.active(),'p active'
     698        assert not p.passive(),'p passive'
     699        assert p.terminated(),'p terminated'
     700        assert not p.interrupted(),'p interrupted'
     701
     702 -   def look5(self, p):
     703        yield hold, self, 11
     704        assert not p.active(),'p active'
     705        assert p.passive(),'p not passive'
     706        assert not p.terminated(),'p terminated'
     707        assert not p.interrupted(),'p interrupted'
     708        self.cancel(p)
     709        assert not p.active(),'p active'
     710        assert p.passive(),'p not passive'
     711        assert not p.terminated(),'p terminated'
     712        assert not p.interrupted(),'p interrupted'
     713
     714 -class PS2(Process):
     715 -   def __init__(self):
     716        Process.__init__(self)
     717
     718 -   def life1(self, res):
     719        yield hold, self, 1
     720        yield request, self, res
     721        yield hold, self, 5
     722        yield request, self, res
     723
     724 -   def life2(self, res):
     725        yield request, self, res
     726        assert self.interrupted(),'p not interrupted'
     727        assert self.queuing(res)
     728        self.interruptReset()
     729        assert not self.interrupted(), 'p interrupted'
     730        assert self.queuing(res)
     731
     732 -class Observer2(Process):
     733 -   def __init__(self):
     734        Process.__init__(self)
     735
     736 -   def look1(self, p1, p2, res):
     737        assert p1.active(), 'p1 not active'
     738        assert not p1.queuing(res), 'p1 queuing'
     739        assert p2.active(), 'p2 noit active'
     740        assert not p2.queuing(res), 'p2 queuing'
     741        yield hold, self, 2
     742        assert p1.active(), 'p1 not active'
     743        assert not p1.queuing(res), 'p1 queuing'
     744        assert p2.passive(), 'p2 active'
     745        assert p2.queuing(res), 'p2 not queuing'
     746
     747 -   def look2(self, p,res):
     748        yield request, self, res
     749        yield hold, self, 5
     750        assert p.passive(),'p not passive'
     751        assert p.queuing(res),'p not queuing for resource'
     752        assert not p.interrupted(), 'p interrupted'
     753        self.interrupt(p)
     754        yield hold, self
     755
     756 -class makePStatetestcase(unittest.TestCase):
     757     """
     758     Tests states and state transitions as defined in SEP003
     759     """
     760
     761 -   def testState1(self):
     762        """
     763        Tests state transitions by hold
     764        """
     765        ## active => hold => terminated
     766        initialize()
     767        p = PS1()
     768        activate(p, p.life1())
     769        ob = Observer1()
     770        activate(ob, ob.look1(p),prior = True)
     771        simulate(until = 12)
     772
     773 -   def testState2(self):
     774        """
     775        Tests state transitions by activate and passivate
     776        """
     777        ## passive => activate => hold => terminated
     778        initialize()
     779        p = PS1()
     780        ob1 = Observer1()
     781        activate(ob1, ob1.look2(p))
     782        simulate(until = 12)
     783        ## passive => activate => hold => active => passivate => passive
     784        initialize()
     785        p1 = PS1()
     786        ob2 = Observer1()
     787        activate(ob2, ob2.look3(p1),prior = True)
     788        simulate(until = 12)
     789
     790 -   def testState3(self):
     791        """
     792        Tests state transitions by cancel()
     793        """
     794        ## active => cancel => passive => reactivate => active => terminated
     795        initialize()
     796        p2 = PS1()
     797        activate(p2, p2.life1())
     798        ob3 = Observer1()
     799        activate(ob3, ob3.look4(p2))
     800        simulate(until = 12)
     801
     802        ## passive => cancel => passive
     803        initialize()
     804        p3 = PS1()
     805        activate(p3, p3.life2())
     806        ob4 = Observer1()
     807        activate(ob4, ob4.look5(p3))
     808        simulate(until = 12)
     809
     810 -   def testState4(self):
     811        """
     812        Test request / release state transitions
     813        """
     814        ## not queuing, active => request => queuing, passive => release => not queuing, active
     815        initialize()
     816        res = Resource(capacity = 1)
     817        pq1 = PS2()
     818        activate(pq1, pq1.life1(res))
     819        pq2 = PS2()
     820        activate(pq2, pq2.life1(res))
     821        obq1 = Observer2()
     822        activate(obq1, obq1.look1(pq1, pq2, res))
     823        simulate(until = 12)
     824
     825        ## queuing, passive => interrupt =>  queuing, interrupted => interruptRest => queuing, not interrupted
     826        initialize()
     827        res = Resource(capacity = 1)
     828        pq3 = PS2()
     829        activate(pq3, pq3.life2(res))
     830        obq2 = Observer2()
     831        activate(obq2, obq2.look2(pq3, res),prior = True)
     832        simulate(until = 12)
     833
     834
     835
     836 -def makePSuite():
     837     suite = unittest.TestSuite()
     838     testState1 = makePStatetestcase('testState1')
     839     testState2 = makePStatetestcase('testState2')
     840     testState3 = makePStatetestcase('testState3')
     841     testState4 = makePStatetestcase('testState4')
     842     suite.addTests([testState1, testState2, testState3, testState4])
     843     return suite
     844
     845  ## -------------------------------------------------------------
     846  ##                    TEST Events / Signals
     847  ## -------------------------------------------------------------
     848
     849 -class SignalProcess(Process):
     850 -   def makeSignal(self, ev1, ev2):
     851        yield hold, self, 1
     852        ev1.signal('from SignalProcess')
     853        while ev2.queues:
     854           nq0 = len(ev2.queues)
     855           ev2.signal('from SignalProcess')
     856           assert len(ev2.queues) == (nq0 - 1),'wrong number of processes dequeued'
     857
     858 -class WaitProcess(Process):
     859 -   def waitForSig(self, ev1):
     860        yield waitevent, self, ev1
     861        assert ev1.waits == [],'not all processes waiting for event out of waiting list'
     862        assert ev1 in self.eventsFired, 'did not record firing event'
     863
     864 -class QueueProcess(Process):
     865 -   def queueForSig(self, ev2):
     866        yield queueevent, self, ev2
     867        assert ev2 in self.eventsFired, 'did not record firing event'
     868
     869 -class SignalProcessOR(Process):
     870 -   def makeSignal(self, ev1, ev2):
     871        yield hold, self, 1
     872        ev1.signal('from SignalProcess')
     873        yield hold, self, 3
     874        assert len(ev2.queues) == QueueProcessOR.nrProcesses, 'wrong number of processes queuing for event ev2'
     875        while ev2.queues:
     876           nq0 = len(ev2.queues)
     877           ev2.signal('from SignalProcess')
     878           assert len(ev2.queues) == (nq0 - 1),'wrong number of processes dequeued'
     879        assert not ev2.queues, 'not all processes queuing for ev2 dequeued'
     880
     881 -class WaitProcessOR(Process):
     882 -   def waitForSig(self, evset):
     883        yield waitevent, self, evset
     884        for e in evset:
     885           assert e.waits == [],'process not out of waiting list for all events in OR'
     886
     887 -class WaitProcessOR1(Process):
     888 -    def signalandwait(self):
     889        e1 = SimEvent()
     890        e1.signal()
     891        e2 = SimEvent()
     892        e2.signal()
     893        yield waitevent, self,[e1, e2]
     894        assert self.eventsFired == [e1, e2],'eventsFired does not report all events'
     895
     896
     897 -class QueueProcessOR(Process):
     898      nrProcesses = 0
     899 -    def __init__(self):
     900          Process.__init__(self)
     901          QueueProcessOR.nrProcesses += 1
     902 -    def queueForSig(self, evset):
     903        yield queueevent, self, evset
     904        occurred = False
     905        for e in evset:
     906            occurred = occurred or (e in self.eventsFired)
     907        assert occurred, 'queuing process activated by wrong event(s)'
     908
     909 -class QueueProcessOR1(Process):
     910 -    def signalandqueue(self):
     911          e1 = SimEvent()
     912          e1.signal()
     913          e2 = SimEvent()
     914          e2.signal()
     915          yield queueevent, self,[e1, e2]
     916          assert self.eventsFired == [e1, e2],\
     917                  '(queueevent) eventsFired does not report all fired events'
     918
     919 -class makeEtestcase(unittest.TestCase):
     920     """
     921     Test SimEvent / signal as introduced with SimPy 1.5
     922     """
     923
     924 -   def testSimEvents1(self):
     925        """
     926        Tests basic signal semantics
     927        """
     928        e = SimEvent()
     929        e.signal('param')
     930        assert e.occurred, 'signal does not set \'occurred\' to True'
     931        assert e.signalparam == 'param', 'signal parameter wrong'
     932        e.signal()
     933        assert e.signalparam is None, 'signal with no parameter did not overwrite signalparam'
     934        e.signal()
     935        assert e.occurred, 'multiple calls to signal do not set \'occurred\''
     936
     937 -   def testSimEvents2(self):
     938        """
     939        Tests basic waiting and queuing semantics
     940        """
     941        initialize()
     942        ev1 = SimEvent('ev1')
     943        ev2 = SimEvent('ev2')
     944        w1 = WaitProcess()
     945        activate(w1, w1.waitForSig(ev1))
     946        w2 = WaitProcess()
     947        activate(w2, w2.waitForSig(ev1))
     948        for i in range(3):
     949           q = QueueProcess()
     950           activate(q, q.queueForSig(ev2))
     951        simulate(until = 2)
     952
     953 -   def testSimEvents3(self):
     954        """
     955        Tests waiting, queuing for at least one event out of a list / tuple.
     956        """
     957        initialize()
     958        e1 = SimEvent('e1')
     959        e2 = SimEvent('e2')
     960        e3 = SimEvent('e3')
     961        s = SignalProcessOR()
     962        activate(s, s.makeSignal(e1, e3))
     963        w = WaitProcessOR()
     964        activate(w, w.waitForSig([e1, e2]))
     965        for i in range(5):
     966           q = QueueProcessOR()
     967           activate(q, q.queueForSig([e2, e3]))
     968        simulate(until = 10)
     969
     970 -   def testSimEvents4(self):
     971        """Tests that eventsFired reports all events which fired
     972        """
     973        initialize()
     974        w = WaitProcessOR1()
     975        activate(w, w.signalandwait())
     976        simulate(until = 5)
     977
     978 -   def testSimEvents5(self):
     979        """Tests that eventsFired reports all events which fired
     980        """
     981        initialize()
     982        w = QueueProcessOR1()
     983        activate(w, w.signalandqueue())
     984        simulate(until = 5)
     985
     986 -def makeESuite():
     987     suite = unittest.TestSuite()
     988     testSimEvents1 = makeEtestcase('testSimEvents1')
     989     testSimEvents2 = makeEtestcase('testSimEvents2')
     990     testSimEvents3 = makeEtestcase('testSimEvents3')
     991     testSimEvents4 = makeEtestcase('testSimEvents4')
     992     testSimEvents5 = makeEtestcase('testSimEvents5')
     993     suite.addTests([testSimEvents1, testSimEvents2, testSimEvents3, testSimEvents4, testSimEvents5])
     994     return suite
     995
     996  ## -------------------------------------------------------------
     997  ##                    TEST waituntil
     998  ## -------------------------------------------------------------
     999
    1000 -class Signaller(Process):
    1001 -    def makeconditions(self, waiter):
    1002          global a, b,c
    1003          a = True
    1004          yield hold, self, 1
    1005          b = True
    1006          yield hold, self, 1
    1007          c = True
    1008          yield hold, self, 1
    1009          assert waiter.terminated(),'waituntil did not fire'
    1010
    1011 -class Waiter(Process):
    1012 -    def waitforit(self):
    1013          def waitcond():
    1014              return a and b and c
    1015          yield waituntil, self, waitcond
    1016
    1017 -class makeWtestcase(unittest.TestCase):
    1018     """
    1019     Test waituntil as introduced with SimPy 1.5
    1020     """
    1021
    1022 -   def testwaituntil1(self):
    1023         global a, b,c
    1024         a = b=c = False
    1025         initialize()
    1026         w = Waiter()
    1027         activate(w, w.waitforit())
    1028         s = Signaller()
    1029         activate(s, s.makeconditions(w))
    1030         simulate(until = 5)
    1031
    1032 -def makeWSuite():
    1033     suite = unittest.TestSuite()
    1034     testwaituntil1 = makeWtestcase('testwaituntil1')
    1035     suite.addTests([testwaituntil1])
    1036     return suite
    1037
    1038  ## -------------------------------------------------------------
    1039  ##                    TEST COMPOUND 'YIELD REQUEST' COMMANDS
    1040  ## -------------------------------------------------------------
    1041
    1042  ## -------------------------------------------------------------
    1043  ##             TEST 'yield (request, self, res),(hold, self, delay)'
    1044  ##                   == timeout renege
    1045  ##             for both unmonitored and monitored resources
    1046  ## -------------------------------------------------------------
    1047
    1048 -class JobTO(Process):
    1049     """ Job class for testing timeout reneging
    1050     """
    1051 -   def __init__(self, server = None, name = ''):
    1052          Process.__init__(self, name)
    1053          self.res = server
    1054          self.gotResource = None
    1055
    1056 -   def execute(self, timeout, usetime):
    1057          yield (request, self, self.res),(hold, self, timeout)
    1058          if self.acquired(self.res):
    1059              self.gotResource = True
    1060              yield hold, self, usetime
    1061              yield release, self, self.res
    1062          else:
    1063              self.gotResource = False
    1064
    1065 -class JobTO_P(Process):
    1066     """ Job class for testing timeout reneging with priorities
    1067     """
    1068 -   def __init__(self, server = None, name = ''):
    1069          Process.__init__(self, name)
    1070          self.res = server
    1071          self.gotResource = None
    1072
    1073 -   def execute(self, timeout, usetime, priority):
    1074          yield (request, self, self.res, priority),(hold, self, timeout)
    1075          if self.acquired(self.res):
    1076              self.gotResource = True
    1077              yield hold, self, usetime
    1078              yield release, self, self.res
    1079          else:
    1080              self.gotResource = False
    1081
    1082 -class makeTimeoutTestcase(unittest.TestCase):
    1083      """ Tests of 'yield (request, self, res),(hold, self, delay)'
    1084          timeout reneging command
    1085      """
    1086 -    def testNoTimeout(self):
    1087          """Test that resource gets acquired without timeout
    1088          """
    1089          res = Resource(name = 'Server', capacity = 1)
    1090          initialize()
    1091          usetime = 5
    1092          timeout = 1000000
    1093          j1 = JobTO(server = res, name = 'Job_1')
    1094          activate(j1, j1.execute(timeout = timeout, usetime = usetime))
    1095          j2 = JobTO(server = res, name = 'Job_2')
    1096          activate(j2, j2.execute(timeout = timeout, usetime = usetime))
    1097          simulate(until = 2 * usetime)
    1098          assert now() == 2 * usetime, 'time not == 2 * usetime'
    1099          assert j1.gotResource and j2.gotResource,\
    1100              'at least one job failed to get resource'
    1101          assert not (res.waitQ or res.activeQ),\
    1102              'job waiting or using resource'
    1103
    1104 -    def testNoTimeoutM(self):
    1105          """Test that resource gets acquired without timeout.
    1106             Resource monitored.
    1107          """
    1108          res = Resource(name = 'Server', capacity = 1, monitored = True)
    1109          initialize()
    1110          usetime = 5
    1111          timeout = 1000000
    1112          j1 = JobTO(server = res, name = 'Job_1')
    1113          activate(j1, j1.execute(timeout = timeout, usetime = usetime))
    1114          j2 = JobTO(server = res, name = 'Job_2')
    1115          activate(j2, j2.execute(timeout = timeout, usetime = usetime))
    1116          simulate(until = 2 * usetime)
    1117          assert now() == 2 * usetime, 'time not == 2 * usetime'
    1118          assert j1.gotResource and j2.gotResource,\
    1119              'at least one job failed to get resource'
    1120          assert not (res.waitQ or res.activeQ),\
    1121              'job waiting or using resource'
    1122          assert res.waitMon == [[0, 1],[usetime, 0]],'res.waitMon wrong: %s'%res.waitMon
    1123
    1124 -    def testTimeout1(self):
    1125          """Test that timeout occurs when resource busy
    1126          """
    1127          res = Resource(name = 'Server', capacity = 1)
    1128          initialize()
    1129          usetime = 5
    1130          timeout = 3
    1131          j1 = JobTO(server = res, name = 'Job_1')
    1132          activate(j1, j1.execute(timeout = timeout, usetime = usetime))
    1133          j2 = JobTO(server = res, name = 'Job_2')
    1134          activate(j2, j2.execute(timeout = timeout, usetime = usetime))
    1135          simulate(until = 2 * usetime)
    1136          assert(now() == usetime),'time not == usetime'
    1137          assert(j1.gotResource),'Job_1 did not get resource'
    1138          assert(not j2.gotResource),'Job_2 did not renege'
    1139          assert not (res.waitQ or res.activeQ),\
    1140              'job waiting or using resource'
    1141
    1142 -    def testTimeout1M(self):
    1143          """Test that timeout occurs when resource busy.
    1144             Resource monitored.
    1145          """
    1146          res = Resource(name = 'Server', capacity = 1, monitored = True)
    1147          initialize()
    1148          usetime = 5
    1149          timeout = 3
    1150          j1 = JobTO(server = res, name = 'Job_1')
    1151          activate(j1, j1.execute(timeout = timeout, usetime = usetime))
    1152          j2 = JobTO(server = res, name = 'Job_2')
    1153          activate(j2, j2.execute(timeout = timeout, usetime = usetime))
    1154          simulate(until = 2 * usetime)
    1155          assert(now() == usetime),'time not == usetime'
    1156          assert(j1.gotResource),'Job_1 did not get resource'
    1157          assert(not j2.gotResource),'Job_2 did not renege'
    1158          assert not (res.waitQ or res.activeQ),\
    1159              'job waiting or using resource'
    1160          assert res.waitMon == [[0, 1],[timeout, 0]],'res.waitMon wrong: %s'%res.waitMon
    1161
    1162 -    def testTimeout_MP(self):
    1163          """Test that timeout occurs when resource busy.
    1164             Resource monitored. Requests with priority and preemption.
    1165          """
    1166          res = Resource(name = 'Server', capacity = 1, monitored = True, qType = PriorityQ, preemptable = True)
    1167          initialize()
    1168          usetime = 5
    1169          timeout = 3
    1170          j1 = JobTO_P(server = res, name = 'Job_1')
    1171          activate(j1, j1.execute(timeout = timeout, usetime = usetime, priority = 1))
    1172          j2 = JobTO_P(server = res, name = 'Job_2')
    1173          j2_arrival = 1
    1174          activate(j2, j2.execute(timeout = timeout, usetime = usetime, priority = 5),at = j2_arrival)
    1175          j3 = JobTO_P(server = res, name = 'Job_2')
    1176          j3_arrival = 2
    1177          activate(j3, j3.execute(timeout = timeout, usetime = usetime, priority = 10),at = j3_arrival)
    1178          simulate(until = 3 * usetime)
    1179          assert(now() == 3 * usetime),'time not == 2 * usetime, but %s'%now()
    1180          assert(j1.gotResource),'Job_1 did not get resource'
    1181          assert(j2.gotResource),'Job_2 did renege'
    1182          assert(j2.gotResource),'Job_3 did renege'
    1183          assert not (res.waitQ or res.activeQ),\
    1184              'job waiting or using resource'
    1185          assert res.waitMon == [[j2_arrival, 1],[j3_arrival, 2],[usetime + j3_arrival, 1],[usetime + j2_arrival + usetime, 0]],\
    1186               'res.waitMon wrong: %s'%res.waitMon
    1187
    1188 -    def testTimeout2(self):
    1189          """Test that timeout occurs when resource has no capacity free
    1190          """
    1191          res = Resource(name = 'Server', capacity = 0)
    1192          initialize()
    1193          usetime = 5
    1194          timeout = 3
    1195          j1 = JobTO(server = res, name = 'Job_1')
    1196          activate(j1, j1.execute(timeout = timeout, usetime = usetime))
    1197          j2 = JobTO(server = res, name = 'Job_2')
    1198          activate(j2, j2.execute(timeout = timeout, usetime = usetime))
    1199          simulate(until = 2 * usetime)
    1200          assert now() == timeout, 'time %s not == timeout'%now()
    1201          assert not j1.gotResource, 'Job_1 got resource'
    1202          assert not j2.gotResource, 'Job_2 got resource'
    1203          assert not (res.waitQ or res.activeQ),\
    1204              'job waiting or using resource'
    1205
    1206 -    def testTimeout2M(self):
    1207          """Test that timeout occurs when resource has no capacity free.
    1208             Resource monitored.
    1209          """
    1210          res = Resource(name = 'Server', capacity = 0, monitored = True)
    1211          initialize()
    1212          usetime = 5
    1213          timeout = 3
    1214          j1 = JobTO(server = res, name = 'Job_1')
    1215          activate(j1, j1.execute(timeout = timeout, usetime = usetime))
    1216          j2 = JobTO(server = res, name = 'Job_2')
    1217          activate(j2, j2.execute(timeout = timeout, usetime = usetime))
    1218          simulate(until = 2 * usetime)
    1219          assert now() == timeout, 'time %s not == timeout'%now()
    1220          assert not j1.gotResource, 'Job_1 got resource'
    1221          assert not j2.gotResource, 'Job_2 got resource'
    1222          assert not (res.waitQ or res.activeQ),\
    1223              'job waiting or using resource'
    1224          assert res.waitMon == [[0, 1],[0, 2],[timeout, 1],[timeout, 0]],\
    1225              'res.waitMon is wrong: %s'%res.waitMon
    1226
    1227 -def makeTOSuite():
    1228      suite = unittest.TestSuite()
    1229      testNoTimeout = makeTimeoutTestcase('testNoTimeout')
    1230      testNoTimeoutM = makeTimeoutTestcase('testNoTimeoutM')
    1231      testTimeout1 = makeTimeoutTestcase('testTimeout1')
    1232      testTimeout1M = makeTimeoutTestcase('testTimeout1M')
    1233      testTimeout_MP = makeTimeoutTestcase('testTimeout_MP')
    1234      testTimeout2 = makeTimeoutTestcase('testTimeout2')
    1235      testTimeout2M = makeTimeoutTestcase('testTimeout2M')
    1236      suite.addTests([testNoTimeout, testNoTimeoutM,
    1237                      testTimeout1, testTimeout1M, testTimeout_MP,
    1238                     testTimeout2, testTimeout2M])
    1239      return suite
    1240
    1241  ## ------------------------------------------------------------------
    1242  ##             TEST 'yield (request, self, res),(waitevent, self, event)'
    1243  ##                   == event renege
    1244  ##             for both unmonitored and monitored resources
    1245  ## ------------------------------------------------------------------
    1246
    1247
    1248 -class JobEvt(Process):
    1249     """ Job class for testing event reneging
    1250     """
    1251 -   def __init__(self, server = None, name = ''):
    1252          Process.__init__(self, name)
    1253          self.res = server
    1254          self.gotResource = None
    1255
    1256 -   def execute(self, event, usetime):
    1257          yield (request, self, self.res),(waitevent, self, event)
    1258          if self.acquired(self.res):
    1259              self.gotResource = True
    1260              yield hold, self, usetime
    1261              yield release, self, self.res
    1262          else:
    1263              self.gotResource = False
    1264
    1265 -class JobEvtMulti(Process):
    1266     """ Job class for testing event reneging with multi - event lists
    1267     """
    1268 -   def __init__(self, server = None, name = ''):
    1269          Process.__init__(self, name)
    1270          self.res = server
    1271          self.gotResource = None
    1272
    1273 -   def execute(self, eventlist, usetime):
    1274          yield (request, self, self.res),(waitevent, self, eventlist)
    1275          if self.acquired(self.res):
    1276              self.gotResource = True
    1277              yield hold, self, usetime
    1278              yield release, self, self.res
    1279          else:
    1280              self.gotResource = False
    1281
    1282 -class FireEvent(Process):
    1283      """Fires reneging event
    1284      """
    1285 -    def fire(self, fireDelay, event):
    1286          yield hold, self, fireDelay
    1287          event.signal()
    1288
    1289 -class makeEventRenegeTestcase(unittest.TestCase):
    1290      """Tests of 'yield (request, self, res),(waiteevent, self, event)'
    1291         event reneging command
    1292      """
    1293 -    def testNoEvent(self):
    1294          """Test that processes acquire resource normally if no event fires
    1295          """
    1296          res = Resource(name = 'Server', capacity = 1)
    1297          event = SimEvent('Renege_trigger') #never gets fired
    1298          initialize()
    1299          usetime = 5
    1300          j1 = JobEvt(server = res, name = 'Job_1')
    1301          activate(j1, j1.execute(event = event, usetime = usetime))
    1302          j2 = JobEvt(server = res, name = 'Job_2')
    1303          activate(j2, j2.execute(event = event, usetime = usetime))
    1304          simulate(until = 2 * usetime)
    1305          # Both jobs should get server (in sequence)
    1306          assert now() == 2 * usetime, 'time not == 2 * usetime'
    1307          assert j1.gotResource and j2.gotResource,\
    1308              'at least one job failed to get resource'
    1309          assert not (res.waitQ or res.activeQ),\
    1310              'job waiting or using resource'
    1311
    1312 -    def testNoEventM(self):
    1313          """Test that processes acquire resource normally if no event fires.
    1314             Resource monitored.
    1315          """
    1316          res = Resource(name = 'Server', capacity = 1, monitored = True)
    1317          event = SimEvent('Renege_trigger') #never gets fired
    1318          initialize()
    1319          usetime = 5
    1320          j1 = JobEvt(server = res, name = 'Job_1')
    1321          activate(j1, j1.execute(event = event, usetime = usetime))
    1322          j2 = JobEvt(server = res, name = 'Job_2')
    1323          activate(j2, j2.execute(event = event, usetime = usetime))
    1324          simulate(until = 2 * usetime)
    1325          # Both jobs should get server (in sequence)
    1326          assert now() == 2 * usetime, 'time not == 2 * usetime'
    1327          assert j1.gotResource and j2.gotResource,\
    1328              'at least one job failed to get resource'
    1329          assert not (res.waitQ or res.activeQ),\
    1330              'job waiting or using resource'
    1331          assert res.waitMon == [[0, 1],[usetime, 0]],'res.waitMoni is wrong: %s'%res.waitMon
    1332
    1333 -    def testWaitEvent1(self):
    1334          """Test that signalled event leads to renege when resource busy
    1335          """
    1336          res = Resource(name = 'Server', capacity = 1)
    1337          initialize()
    1338          event = SimEvent('Renege_trigger')
    1339          usetime = 5
    1340          eventtime = 1
    1341          j1 = JobEvt(server = res, name = 'Job_1')
    1342          activate(j1, j1.execute(event = event, usetime = usetime))
    1343          j2 = JobEvt(server = res, name = 'Job_2')
    1344          activate(j2, j2.execute(event = event, usetime = usetime))
    1345          f = FireEvent(name = 'FireEvent')
    1346          activate(f, f.fire(fireDelay = eventtime, event = event))
    1347          simulate(until = 2 * usetime)
    1348          # Job_1 should get server, Job_2 renege
    1349          assert(now() == usetime),'time not == usetime'
    1350          assert(j1.gotResource),'Job_1 did not get resource'
    1351          assert(not j2.gotResource),'Job_2 did not renege'
    1352          assert not (res.waitQ or res.activeQ),\
    1353              'job waiting or using resource'
    1354
    1355 -    def testWaitEvent1M(self):
    1356          """Test that signalled event leads to renege when resource busy.
    1357             Resource monitored.
    1358          """
    1359          res = Resource(name = 'Server', capacity = 1, monitored = True)
    1360          initialize()
    1361          event = SimEvent('Renege_trigger')
    1362          usetime = 5
    1363          eventtime = 1
    1364          j1 = JobEvt(server = res, name = 'Job_1')
    1365          activate(j1, j1.execute(event = event, usetime = usetime))
    1366          j2 = JobEvt(server = res, name = 'Job_2')
    1367          activate(j2, j2.execute(event = event, usetime = usetime))
    1368          f = FireEvent(name = 'FireEvent')
    1369          activate(f, f.fire(fireDelay = eventtime, event = event))
    1370          simulate(until = 2 * usetime)
    1371          # Job_1 should get server, Job_2 renege
    1372          assert(now() == usetime),'time not == usetime'
    1373          assert(j1.gotResource),'Job_1 did not get resource'
    1374          assert(not j2.gotResource),'Job_2 did not renege'
    1375          assert not (res.waitQ or res.activeQ),\
    1376              'job waiting or using resource'
    1377          assert res.waitMon == [[0, 1],[eventtime, 0]],'res.waitMon is wrong: %s'%res.waitMon
    1378
    1379 -    def testWaitEvent2(self):
    1380          """Test that renege - triggering event can be one of an event list
    1381          """
    1382          res = Resource(name = 'Server', capacity = 1)
    1383          initialize()
    1384          event1 = SimEvent('Renege_trigger_1')
    1385          event2 = SimEvent('Renege_trigger_2')
    1386          usetime = 5
    1387          eventtime = 1 #for both events
    1388          j1 = JobEvtMulti(server = res, name = 'Job_1')
    1389          activate(j1, j1.execute(eventlist = [event1, event2],usetime = usetime))
    1390          j2 = JobEvtMulti(server = res, name = 'Job_2')
    1391          activate(j2, j2.execute(eventlist = [event1, event2],usetime = usetime))
    1392          f1 = FireEvent(name = 'FireEvent_1')
    1393          activate(f1, f1.fire(fireDelay = eventtime, event = event1))
    1394          f2 = FireEvent(name = 'FireEvent_2')
    1395          activate(f2, f2.fire(fireDelay = eventtime, event = event2))
    1396          simulate(until = 2 * usetime)
    1397          # Job_1 should get server, Job_2 should renege
    1398          assert(now() == usetime),'time not == usetime'
    1399          assert(j1.gotResource),'Job_1 did not get resource'
    1400          assert(not j2.gotResource),'Job_2 did not renege'
    1401          assert not (res.waitQ or res.activeQ),\
    1402              'job waiting or using resource'
    1403
    1404 -    def testWaitEvent2M(self):
    1405          """Test that renege - triggering event can be one of an event list.
    1406             Resource monitored.
    1407          """
    1408          res = Resource(name = 'Server', capacity = 1, monitored = True)
    1409          initialize()
    1410          event1 = SimEvent('Renege_trigger_1')
    1411          event2 = SimEvent('Renege_trigger_2')
    1412          usetime = 5
    1413          eventtime = 1 #for both events
    1414          j1 = JobEvtMulti(server = res, name = 'Job_1')
    1415          activate(j1, j1.execute(eventlist = [event1, event2],usetime = usetime))
    1416          j2 = JobEvtMulti(server = res, name = 'Job_2')
    1417          activate(j2, j2.execute(eventlist = [event1, event2],usetime = usetime))
    1418          f1 = FireEvent(name = 'FireEvent_1')
    1419          activate(f1, f1.fire(fireDelay = eventtime, event = event1))
    1420          f2 = FireEvent(name = 'FireEvent_2')
    1421          activate(f2, f2.fire(fireDelay = eventtime, event = event2))
    1422          simulate(until = 2 * usetime)
    1423          # Job_1 should get server, Job_2 should renege
    1424          assert(now() == usetime),'time not == usetime'
    1425          assert(j1.gotResource),'Job_1 did not get resource'
    1426          assert(not j2.gotResource),'Job_2 did not renege'
    1427          assert not (res.waitQ or res.activeQ),\
    1428              'job waiting or using resource'
    1429          assert res.waitMon == [[0, 1],[eventtime, 0]],'res.waitMon is wrong: %s'%res.waitMon
    1430
    1431 -def makeEvtRenegeSuite():
    1432      suite = unittest.TestSuite()
    1433      testNoEvent = makeEventRenegeTestcase('testNoEvent')
    1434      testNoEventM = makeEventRenegeTestcase('testNoEventM')
    1435      testWaitEvent1 = makeEventRenegeTestcase('testWaitEvent1')
    1436      testWaitEvent1M = makeEventRenegeTestcase('testWaitEvent1M')
    1437      testWaitEvent2 = makeEventRenegeTestcase('testWaitEvent2')
    1438      testWaitEvent2M = makeEventRenegeTestcase('testWaitEvent2M')
    1439
    1440      suite.addTests([testNoEvent, testNoEventM, testWaitEvent1, testWaitEvent1M,
    1441                      testWaitEvent2, testWaitEvent2M])
    1442      return suite
    1443
    1444  #---Buffer tests (post 1.6.1)-------------------------------------
    1445  ## ------------------------------------------------------------------
    1446  ##             TEST 'yield get, self, level, whatToGet' and
    1447  ##                  'yield put, self, level, whatToPut, priority'
    1448  ##             for Level instances
    1449  ## ------------------------------------------------------------------
    1450 -class Producer(Process):
    1451      produced = 0
    1452 -    def produce(self, buffer):
    1453          for i in range(4):
    1454              Producer.produced += 1
    1455              yield put, self, buffer
    1456              yield hold, self, 1
    1457 -    def producePriority(self, buffer, priority):
    1458          """PriorityQ for Producers"""
    1459          Producer.produced += 4
    1460          yield put, self, buffer, 4,priority
    1461          yield hold, self, 1
    1462          self.done = now()
    1463          doneList.append(self.name)
    1464 -    def produce1(self, buffer):
    1465          for i in range(4):
    1466              yield put, self, buffer, 4
    1467              yield hold, self, 1
    1468 -class Consumer(Process):
    1469      consumed = 0
    1470 -    def consume(self, buffer):
    1471          """FIFO"""
    1472          yield get, self, buffer
    1473          Consumer.consumed += 1
    1474          assert self.got == 1, 'wrong self.got: %s'%self.got
    1475          yield get, self, buffer, 3
    1476          Consumer.consumed += 3
    1477          assert self.got == 3, 'wrong self.got: %s'%self.got
    1478
    1479 -    def consume1(self, buffer):
    1480          """producer PriorityQ, consumer FIFO"""
    1481          while True:
    1482              yield get, self, buffer, 2
    1483              yield hold, self, 1
    1484 -    def consumePriority(self, buffer, priority):
    1485          """PriorityQ for Consumers"""
    1486          yield get, self, buffer, 4,priority
    1487          doneList.append(self.name)
    1488
    1489  ### Begin classes for testConPrinciple (Level) ###
    1490 -class  ProducerPrincL(Process):
    1491 -    def produce(self, buffer, productionTime):
    1492          while True:
    1493              assert not(buffer.amount > 0 and len(buffer.getQ) > 0),\
    1494                  'Consumer(s) waiting while buffer not empty'
    1495              yield hold, self, productionTime
    1496              yield put, self, buffer, 1
    1497
    1498 -class ConsumerPrincL(Process):
    1499 -    def consume(self, buffer, consumptionTime):
    1500          while True:
    1501              assert not(buffer.amount == 0 and len(buffer.putQ) > 0),\
    1502                  'Producer(s) waiting while buffer empty'
    1503              yield get, self, buffer, 1
    1504              yield hold, self, consumptionTime
    1505
    1506  ### End classes for testConPrinciple (Level) ###
    1507
    1508 -class makeLevelTestcase(unittest.TestCase):
    1509 -    def testStatic(self):
    1510          """Tests initialization of Level instances
    1511          """
    1512          a = Level()
    1513          assert a.capacity == sys.maxint, 'wrong capacity:%s'%a
    1514          assert a.amount == 0, 'wrong buffer content: %s'%a
    1515          assert a.name == 'a_level', 'wrong name: %s'%a
    1516          assert not a.monitored, 'should not be monitored: %s'%a
    1517          assert a.putQMon is None, 'should not have putQMon: %s'%a
    1518          assert a.getQMon is None, 'should not have getQMon: %s'%a
    1519          assert a.bufferMon is None, 'should not have bufferMon: %s'%a
    1520          assert a.putQType.__name__ == 'FIFO' and a.getQType.__name__ == 'FIFO',\
    1521                 'putQType and getQType should be FIFO: %s'%a
    1522
    1523          b = Level(name = 'b', initialBuffered = 10.0, monitored = True, capacity = 12,
    1524                      putQType = PriorityQ)
    1525          a = Level()
    1526          assert b.capacity == 12, 'wrong capacity:%s'%b
    1527          assert b.amount == 10, 'wrong buffer content: %s'%b
    1528          assert b.name == 'b', 'wrong name: %s'%b
    1529          assert b.monitored, 'should be monitored: %s'%b
    1530          assert not (b.putQMon is None),'should have putQMon: %s'%b
    1531          assert not (b.getQMon is None),'should have getQMon: %s'%b
    1532          assert not (b.bufferMon is None),'should have bufferMon: %s'%b
    1533          assert b.putQType.__name__ == 'PriorityQ',\
    1534                 'putQType should be PriorityQ: %s'%b
    1535          assert b.getQType.__name__ == 'FIFO',\
    1536                  'getQType should be PriorityQ: %s'%b
    1537
    1538 -    def testConProdPrinciple(self):
    1539          """Level: tests basic Producer / Consumer principles:
    1540          -   Consumers must not be waiting while Level buffer value > 0,
    1541          -   Producers must not be waiting while Level buffer value == 0
    1542          """
    1543          bufferSize = 1
    1544          productionTime = 1
    1545          consumptionTime = 5
    1546          endtime = 50
    1547
    1548          initialize()
    1549          buffer = Level(capacity = bufferSize)
    1550          consumer = ConsumerPrincL()
    1551          activate(consumer, consumer.consume(buffer, consumptionTime))
    1552          producer = ProducerPrincL()
    1553          activate(producer, producer.produce(buffer, productionTime))
    1554          simulate(until = endtime)
    1555
    1556 -    def testConProd1(self):
    1557          """Level: tests put / get in 1 Producer / 1 Consumer scenario"""
    1558          initialize()
    1559          buffer = Level(initialBuffered = 0)
    1560          p = Producer()
    1561          activate(p, p.produce(buffer))
    1562          c = Consumer()
    1563          activate(c, c.consume(buffer))
    1564          simulate(until = 100)
    1565          assert Producer.produced - Consumer.consumed == buffer.amount,\
    1566              'items produced / consumed / buffered do not tally: %s %s %s'\
    1567                  %(Producer.produced, Consumer.consumed, buffer.amount)
    1568
    1569 -    def testConProdM(self):
    1570          """Level: tests put / get in multiple Producer / Consumer scenario"""
    1571          initialize()
    1572          buffer = Level(initialBuffered = 0)
    1573          Producer.produced = 0
    1574          Consumer.consumed = 0
    1575          for i in range(2):
    1576              c = Consumer()
    1577              activate(c, c.consume(buffer))
    1578          for i in range(3):
    1579              p = Producer()
    1580              activate(p, p.produce(buffer))
    1581          simulate(until = 10)
    1582          assert Producer.produced - Consumer.consumed == buffer.amount,\
    1583              'items produced / consumed / buffered do not tally: %s %s %s'\
    1584                  %(Producer.produced, Consumer.consumed, buffer.amount)
    1585
    1586 -    def testConProdPriorM(self):
    1587          """Level: tests put / get in multiple Producer / Consumer scenario,
    1588          with Producers having different priorities.
    1589          How: Producers forced to queue; all after first should be done in
    1590          priority order
    1591          """
    1592          global doneList
    1593          doneList = []
    1594          initialize()
    1595          buffer = Level(capacity = 7, putQType = PriorityQ, monitored = True)
    1596          for i in range(4):
    1597              p = Producer(str(i))
    1598              pPriority = i
    1599              activate(p, p.producePriority(buffer = buffer, priority = pPriority))
    1600          c = Consumer()
    1601          activate(c, c.consume1(buffer = buffer))
    1602          simulate(until = 100)
    1603          assert doneList == ["0", "3","2", "1"],'puts were not done in priority order: %s'\
    1604                                      %doneList
    1605
    1606 -    def testConPriorProdM(self):
    1607          """Level: tests put / get in multiple Producer / Consumer scenario, with
    1608          Consumers having different priorities.
    1609          How: Consumers forced to queue; all after first should be done in
    1610          priority order
    1611          """
    1612          global doneList
    1613          doneList = []
    1614          initialize()
    1615          buffer = Level(capacity = 7, getQType = PriorityQ, monitored = True)
    1616          for i in range(4):
    1617              c = Consumer(str(i))
    1618              cPriority = i
    1619              activate(c, c.consumePriority(buffer = buffer, priority = cPriority))
    1620          p = Producer()
    1621          activate(p, p.produce1(buffer = buffer))
    1622          simulate(until = 100)
    1623          assert doneList == ["3", "2","1", "0"],'gets were not done in priority order: %s'\
    1624                                      %doneList
    1625
    1626 -def makeLevelSuite():
    1627      suite = unittest.TestSuite()
    1628      testStatic = makeLevelTestcase('testStatic')
    1629      testConProdPrinciple = makeLevelTestcase('testConProdPrinciple')
    1630      testConProd1 = makeLevelTestcase('testConProd1')
    1631      testConProdM = makeLevelTestcase('testConProdM')
    1632      testConProdPriorM = makeLevelTestcase('testConProdPriorM')
    1633      testConPriorProdM = makeLevelTestcase('testConPriorProdM')
    1634      suite.addTests([testStatic, testConProdPrinciple, testConProd1,
    1635                      testConProdM, testConProdPriorM,
    1636                      testConPriorProdM])
    1637      return suite
    1638
    1639  ## ------------------------------------------------------------------
    1640  ##             TEST 'yield get, self, store, whatToGet' and
    1641  ##                  'yield put, self, store, whatToPut'
    1642  ##             for Store instances
    1643  ## ------------------------------------------------------------------
    1644
    1645 -class ProducerWidget(Process):
    1646      produced = 0
    1647 -    def produce(self, buffer):
    1648          for i in range(4):
    1649              ProducerWidget.produced += 1
    1650              yield put, self, buffer,[Widget(weight = 5)]
    1651              yield hold, self, 1
    1652 -    def producePriority(self, buffer, priority):
    1653          """PriorityQ for Producers"""
    1654          ProducerWidget.produced += 4
    1655          toStore = [Widget(weight = 5)] * 4
    1656          yield put, self, buffer, toStore, priority
    1657          yield hold, self, 1
    1658          self.done = now()
    1659          doneList.append(self.name)
    1660 -    def produce1(self, buffer):
    1661          for i in range(4):
    1662              yield put, self, buffer,[Widget(weight = 5)] * 4
    1663              yield hold, self, 1
    1664 -    def produceUnordered(self, buffer):
    1665          produced = [Widget(weight = i) for i in [9, 1,8, 2,7, 3,6, 4,5]]
    1666          yield put, self, buffer, produced
    1667
    1668 -class ConsumerWidget(Process):
    1669      consumed = 0
    1670 -    def consume(self, buffer):
    1671          """FIFO"""
    1672          yield get, self, buffer
    1673          ConsumerWidget.consumed += 1
    1674          assert len(self.got) == 1, 'wrong self.got: %s'%self.got
    1675          yield get, self, buffer, 3
    1676          ConsumerWidget.consumed += 3
    1677          assert len(self.got) == 3, 'wrong self.got: %s'%self.got
    1678
    1679 -    def consume1(self, buffer):
    1680          """producer PriorityQ, consumer FIFO"""
    1681          while True:
    1682              yield get, self, buffer, 2
    1683              yield hold, self, 1
    1684
    1685 -    def consumePriority(self, buffer, priority):
    1686          """PriorityQ for Consumers"""
    1687          yield get, self, buffer, 4,priority
    1688          doneList.append(self.name)
    1689
    1690 -    def consumeSorted(self, buffer, gotten):
    1691          yield get, self, buffer
    1692          gotten.append(self.got[0].weight)
    1693
    1694 -class Widget:
    1695 -    def __init__(self, weight):
    1696          self.weight = weight
    1697
    1698 -def mySortFunc(self, par):
    1699      """Sorts Widget instances by weight attribute."""
    1700      tmplist = [(x.weight, x) for x in par]
    1701      tmplist.sort()
    1702      return [x for (key, x) in tmplist]
    1703
    1704  ### Begin classes for testConPrinciple (Store) ###
    1705 -class  ProducerPrincS(Process):
    1706 -    def produce(self, buffer, productionTime):
    1707          while True:
    1708              assert not(buffer.nrBuffered > 0 and len(buffer.getQ) > 0),\
    1709                  'Consumer(s) waiting while buffer not empty'
    1710              yield hold, self, productionTime
    1711              product = WidgetPrinc()
    1712              yield put, self, buffer,[product]
    1713
    1714 -class ConsumerPrincS(Process):
    1715 -    def consume(self, buffer, consumptionTime):
    1716          while True:
    1717              assert not(buffer.nrBuffered == 0 and buffer.putQ),\
    1718                  'Producer(s) waiting while buffer empty'
    1719              yield get, self, buffer, 1
    1720              yield hold, self, consumptionTime
    1721
    1722 -class WidgetPrinc:
    1723      pass
    1724
    1725 -class FilterConsumer(Process):
    1726      """Used in testBufferFilter"""
    1727 -    class Widget:
    1728 -        def __init__(self, weighs):
    1729              self.weight = weighs
    1730
    1731 -    def getItems(self, store, a,b):
    1732          """get all items with weight between a and b"""
    1733          def between_a_and_b(buf):
    1734              res = []
    1735              for item in buf:
    1736                  if a < item.weight < b:
    1737                      res.append(item)
    1738
    1739          all = store.buffered
    1740          yield get, self, store, between_a_and_b
    1741          'All retrieved items weight in range?'
    1742          for it in self.got:
    1743              assert a < it.weight < b, 'weight %s not in range %s..%s'\
    1744                                   %(it.weight, a,b)
    1745          'Any item fitting filter pred left in buffer?'
    1746          for it in store.buffer:
    1747              assert not (a < it.weight < b),\
    1748                  'item left in buffer which fits filter (%s<%s<%s)'\
    1749                  %(a, it.weight, b)
    1750          'All items either in store.buffer of self.got?'
    1751          for it in all:
    1752              assert (it in self.buffer) or (it in self.got),\
    1753                     'item w. weight %s neither in store nor in got'%it.weight
    1754
    1755  ### End classes for testConPrinciple (Store) ###
    1756
    1757 -class makeStoreTestcase(unittest.TestCase):
    1758 -    def testStatic(self):
    1759          """Store: tests initialization of Store instances
    1760          """
    1761          a = Store()
    1762          assert a.capacity == sys.maxint, 'wrong capacity:%s'%a
    1763          assert a.nrBuffered == 0, 'wrong buffer content: %s'%a
    1764          assert a.name == 'a_store', 'wrong name: %s'%a
    1765          assert not a.monitored, 'should not be monitored: %s'%a
    1766          assert a.putQMon is None, 'should not have putQMon: %s'%a
    1767          assert a.getQMon is None, 'should not have getQMon: %s'%a
    1768          assert a.bufferMon is None, 'should not have bufferMon: %s'%a
    1769          assert a.putQType.__name__ == 'FIFO' and a.getQType.__name__ == 'FIFO',\
    1770                 'putQType and getQType should be FIFO: %s'%a
    1771
    1772          stored = [Widget(weight = 5)] * 10
    1773          b = Store(name = 'b', initialBuffered = stored, monitored = True, capacity = 12,
    1774                      putQType = PriorityQ)
    1775          assert b.capacity == 12, 'wrong capacity:%s'%b
    1776          assert b.nrBuffered == 10, 'wrong buffer content: %s'%b
    1777          assert b.name == 'b', 'wrong name: %s'%b
    1778          assert b.monitored, 'should be monitored: %s'%b
    1779          assert not (b.putQMon is None),'should have putQMon: %s'%b
    1780          assert not (b.getQMon is None),'should have getQMon: %s'%b
    1781          assert not (b.bufferMon is None),'should have bufferMon: %s'%b
    1782          assert b.putQType.__name__ == 'PriorityQ',\
    1783                 'putQType should be PriorityQ: %s'%b
    1784          assert b.getQType.__name__ == 'FIFO',\
    1785                  'getQType should be PriorityQ: %s'%b
    1786
    1787 -    def testConProdPrinciple(self):
    1788          """Store: tests basic Producer / Consumer principles:
    1789          -   Consumers must not be waiting while items in Store buffer,
    1790          -   Producers must not be waiting while space available in Store buffer
    1791          """
    1792          bufferSize = 1
    1793          productionTime = 1
    1794          consumptionTime = 5
    1795          endtime = 50
    1796
    1797          initialize()
    1798          buffer = Store(capacity = bufferSize)
    1799          consumer = ConsumerPrincS()
    1800          activate(consumer, consumer.consume(buffer, consumptionTime))
    1801          producer = ProducerPrincS()
    1802          activate(producer, producer.produce(buffer, productionTime))
    1803          simulate(until = endtime)
    1804
    1805 -    def testConProd1(self):
    1806          """Store: tests put / get in 1 Producer / 1 Consumer scenario"""
    1807          initialize()
    1808          buffer = Store(initialBuffered = [])
    1809          p = ProducerWidget()
    1810          activate(p, p.produce(buffer))
    1811          c = ConsumerWidget()
    1812          activate(c, c.consume(buffer))
    1813          simulate(until = 100)
    1814          assert \
    1815             ProducerWidget.produced - ConsumerWidget.consumed == buffer.nrBuffered,\
    1816             'items produced / consumed / buffered do not tally: %s %s %s'\
    1817             %(ProducerWidget.produced, ConsumerWidget.consumed, buffer.nrBuffered)
    1818
    1819 -    def testConProdM(self):
    1820          """Store: tests put / get in multiple Producer / Consumer scenario"""
    1821          initialize()
    1822          buffer = Store(initialBuffered = [])
    1823          ProducerWidget.produced = 0
    1824          ConsumerWidget.consumed = 0
    1825          for i in range(2):
    1826              c = ConsumerWidget()
    1827              activate(c, c.consume(buffer))
    1828          for i in range(3):
    1829              p = ProducerWidget()
    1830              activate(p, p.produce(buffer))
    1831          simulate(until = 10)
    1832          assert ProducerWidget.produced - ConsumerWidget.consumed == buffer.nrBuffered,\
    1833              'items produced / consumed / buffered do not tally: %s %s %s'\
    1834              %(ProducerWidget.produced, ConsumerWidget.consumed, buffer.nrBuffered)
    1835
    1836 -    def testConProdPriorM(self):
    1837          """Store: Tests put / get in multiple Producer / Consumer scenario,
    1838          with Producers having different priorities.
    1839          How; Producers forced to queue; all after first should be done in
    1840          priority order
    1841          """
    1842          global doneList
    1843          doneList = []
    1844          initialize()
    1845          buffer = Store(capacity = 7, putQType = PriorityQ, monitored = True)
    1846          for i in range(4):
    1847              p = ProducerWidget(str(i))
    1848              pPriority = i
    1849              activate(p, p.producePriority(buffer = buffer, priority = pPriority))
    1850          c = ConsumerWidget()
    1851          activate(c, c.consume1(buffer = buffer))
    1852          simulate(until = 100)
    1853          assert doneList == ["0", "3","2", "1"],'puts were not done in priority order: %s'\
    1854                                      %doneList
    1855
    1856 -    def testConPriorProdM(self):
    1857          """Tests put / get in multiple Producer / Consumer scenario, with
    1858          Consumers having different priorities.
    1859          How; Consumers forced to queue; all after first should be done in
    1860          priority order
    1861          """
    1862          global doneList
    1863          doneList = []
    1864          initialize()
    1865          buffer = Store(capacity = 7, getQType = PriorityQ, monitored = True)
    1866          for i in range(4):
    1867              c = ConsumerWidget(str(i))
    1868              cPriority = i
    1869              activate(c, c.consumePriority(buffer = buffer, priority = cPriority))
    1870          p = ProducerWidget()
    1871          activate(p, p.produce1(buffer = buffer))
    1872          simulate(until = 100)
    1873          assert doneList == ['3', '2', '1', '0'],\
    1874                'gets were not done in priority order: %s'%doneList
    1875
    1876 -    def testBufferSort(self):
    1877          """Tests the optional sorting of theBuffer by applying a user - defined
    1878          sort function."""
    1879          initialize()
    1880          gotten = []
    1881          sortedStore = Store()
    1882          sortedStore.addSort(mySortFunc)
    1883          p = ProducerWidget()
    1884          activate(p, p.produceUnordered(sortedStore))
    1885          for i in range(9):
    1886              c = ConsumerWidget()
    1887              activate(c, c.consumeSorted(buffer = sortedStore, gotten = gotten),at = 1)
    1888          simulate(until = 10)
    1889          assert gotten == [1, 2,3, 4,5, 6,7, 8,9],'sort wrong: %s'%gotten
    1890
    1891 -    def testBufferFilter(self):
    1892          """Tests get from a Store with a filter function
    1893          """
    1894          initialize()
    1895          ItClass = FilterConsumer.Widget
    1896          all = [ItClass(1),ItClass(4),ItClass(6),ItClass(12)]
    1897          st = Store(initialBuffered = all)
    1898          fc = FilterConsumer()
    1899          minw = 2;maxw = 10
    1900          activate(fc, fc.getItems(store = st, a = minw, b = maxw))
    1901          simulate(until = 1)
    1902
    1903 -def makeStoreSuite():
    1904      suite = unittest.TestSuite()
    1905      testStatic = makeStoreTestcase('testStatic')
    1906      testConProdPrinciple = makeStoreTestcase('testConProdPrinciple')
    1907      testConProd1 = makeStoreTestcase('testConProd1')
    1908      testConProdM = makeStoreTestcase('testConProdM')
    1909      testConProdPriorM = makeStoreTestcase('testConProdPriorM')
    1910      testConPriorProdM = makeStoreTestcase('testConPriorProdM')
    1911      testBufferSort = makeStoreTestcase('testBufferSort')
    1912      testBufferFilter = makeStoreTestcase('testBufferFilter')
    1913      suite.addTests([testStatic, testConProdPrinciple, testConProd1,
    1914                      testConProdM, testConProdPriorM,
    1915                      testConPriorProdM, testBufferSort,
    1916                      testBufferFilter])
    1917      return suite
    1918
    1919  ## ------------------------------------------------------------------
    1920  ##
    1921  ##  Store: Tests for compound get / put
    1922  ##
    1923  ## ------------------------------------------------------------------
    1924 -class TBT(Process):
    1925      """Store: For testBasicTime"""
    1926 -    def tbt(self, store):
    1927          yield get, self, store, 1
    1928          assert self.got, 'Did not get Item'
    1929          yield (get, self, store, 1),(hold, self, 5)
    1930          if self.acquired(store):
    1931              assert len(self.got) == 1, 'did not get 1 Item'
    1932          else:
    1933              assert not self.got and now() == 5 and not store.getQ,\
    1934                     'time renege not working'
    1935
    1936 -class TBE(Process):
    1937      """Store: For testBasicEvent"""
    1938 -    def tbe(self, store, trigger):
    1939          yield get, self, store, 1
    1940          assert self.got, 'Did not get Item'
    1941          yield (get, self, store, 1),(waitevent, self, trigger)
    1942          if self.acquired(store):
    1943              assert False, 'should have reneged'
    1944          else:
    1945              assert self.eventsFired[0] == trigger and now() == 5 \
    1946                  and not store.getQ, 'event renege not working'
    1947
    1948 -class TBEtrigger(Process):
    1949      """Store: For testBasicEvent"""
    1950 -    def fire(self, trigger):
    1951          yield hold, self, 5
    1952          trigger.signal()
    1953
    1954 -class makeStoreCompTestcase(unittest.TestCase):
    1955      """Store: Testcase for compound get statements"""
    1956
    1957 -class TBTput(Process):
    1958      """Store: for testBasicTimePut"""
    1959 -    def tbt(self, store):
    1960          class Item:pass
    1961          yield (put, self, store,[Item()]),(hold, self, 4)
    1962          if self.stored(store):
    1963              assert store.nrBuffered == 1 and not store.putQ,\
    1964                     'put did not execute'
    1965          else:
    1966              assert False, 'should not have reneged'
    1967          yield (put, self, store,[Item()]),(hold, self, 5)
    1968          if self.stored(store):
    1969              assert False, 'should have reneged'
    1970          else:
    1971              assert store.nrBuffered == 1 and not store.putQ,\
    1972                     'renege not working correctly'
    1973
    1974 -class TBEput(Process):
    1975      """Store: for testBasicEventPut"""
    1976 -    def tbe(self, store, trigger):
    1977          class Item:pass
    1978          yield (put, self, store,[Item()]),(waitevent, self, trigger)
    1979          if self.stored(store):
    1980              assert store.nrBuffered == 1 and not store.putQ,\
    1981                     'put did not execute'
    1982          else:
    1983              assert False, 'should have not have reneged'
    1984          yield (put, self, store,[Item()]),(waitevent, self, trigger)
    1985          if self.stored(store):
    1986              assert False, 'should have reneged'
    1987          else:
    1988              assert now() == 5 and self.eventsFired[0] == trigger\
    1989                     and not store.putQ, 'renege not working correctly'
    1990
    1991 -class TBEtriggerPut(Process):
    1992      """Store: For testBasicEventPut"""
    1993 -    def fire(self, trigger):
    1994          yield hold, self, 5
    1995          trigger.signal()
    1996
    1997 -class makeStoreCompTestcase(unittest.TestCase):
    1998      """Store: Testcase for compound get statements"""
    1999      ## ------------------------------------------------------------------
    2000      ##             TEST 'yield (get, self, store),(hold, self, time)'
    2001      ##                   == timeout renege
    2002      ##             for both unmonitored and monitored Stores
    2003      ## ------------------------------------------------------------------
    2004
    2005 -    def testBasicTime(self):
    2006          """Store (unmonitored):
    2007          test 'yield (get, self, store),(hold, self, timeout)"""
    2008          class Item:pass
    2009          initialize()
    2010          st = Store(initialBuffered = [Item()])
    2011          t = TBT()
    2012          activate(t, t.tbt(store = st))
    2013          simulate(until = 10)
    2014
    2015
    2016      ## ------------------------------------------------------------------
    2017      ##             TEST 'yield (put, self, store),(hold, self, time)'
    2018      ##                   == timeout renege
    2019      ##             for both unmonitored and monitored Stores
    2020      ## ------------------------------------------------------------------
    2021 -    def testBasicTimePut(self):
    2022          """Store (unmonitored):
    2023          test 'yield (put, self, store),(hold, self, time)"""
    2024          initialize()
    2025          st = Store(capacity = 1)
    2026          t = TBTput()
    2027          activate(t, t.tbt(store = st))
    2028          simulate(until = 10)
    2029
    2030 -    def testBasicTimePutM(self):
    2031          """Store (monitored):
    2032          test monitors with 'yield (put, self, store),(hold, self, time)"""
    2033          initialize()
    2034          st = Store(capacity = 1, monitored = True)
    2035          t = TBTput()
    2036          activate(t, t.tbt(store = st))
    2037          simulate(until = 10)
    2038          #First put succeeds, second attempt reneges at t = 5?
    2039          assert st.putQMon == [[0, 0],[0, 1],[5, 0]],'putQMon wrong: %s'\
    2040                                                 %st.putQMon
    2041          #First Item goes into buffer at t = 0, second not (renege)?
    2042          assert st.bufferMon == [[0, 0],[0, 1]],'bufferMon wrong: %s'%st.bufferMon
    2043
    2044
    2045      ## ------------------------------------------------------------------
    2046      ##             TEST 'yield (get, self, store),(waitevent, self, event)'
    2047      ##                   == event renege
    2048      ##             for both unmonitored and monitored Stores
    2049      ## ------------------------------------------------------------------
    2050 -    def testBasicEvent(self):
    2051          """Store (unmonitored):
    2052          test 'yield (get, self, store),(waitevent, self, event)"""
    2053          class Item:pass
    2054          initialize()
    2055          st = Store(initialBuffered = [Item()])
    2056          trig = SimEvent()
    2057          t = TBE()
    2058          activate(t, t.tbe(store = st, trigger = trig))
    2059          tr = TBEtrigger()
    2060          activate(tr, tr.fire(trigger = trig))
    2061          simulate(until = 10)
    2062
    2063
    2064      ## ------------------------------------------------------------------
    2065      ##             TEST 'yield (put, self, store),(waitevent, self, event)'
    2066      ##                   == event renege
    2067      ##             for both unmonitored and monitored Stores
    2068      ## ------------------------------------------------------------------
    2069 -    def testBasicEventPut(self):
    2070          """Store (unmonitored):
    2071          test 'yield (put, self, store),(waitevent, self, event)"""
    2072          initialize()
    2073          s = SimEvent()
    2074          store = Store(capacity = 1)
    2075          t = TBEtriggerPut()
    2076          activate(t, t.fire(trigger = s))
    2077          tb = TBEput()
    2078          activate(tb, tb.tbe(store = store, trigger = s))
    2079          simulate(until = 10)
    2080
    2081 -    def testBasicEventPutM(self):
    2082          """Store (monitored):
    2083          test monitors with 'yield (put, self, store),(waitevent, self, event)"""
    2084          initialize()
    2085          s = SimEvent()
    2086          st = Store(capacity = 1, monitored = True)
    2087          t = TBEtriggerPut()
    2088          activate(t, t.fire(trigger = s))
    2089          tb = TBEput()
    2090          activate(tb, tb.tbe(store = st, trigger = s))
    2091          simulate(until = 10)
    2092          #First put succeeds, second attempt reneges at t = 5?
    2093          assert st.putQMon == [[0, 0],[0, 1],[5, 0]],'putQMon wrong: %s'\
    2094                                                 %st.putQMon
    2095          #First Item goes into buffer at t = 0, second not (renege)?
    2096          assert st.bufferMon == [[0, 0],[0, 1]],'bufferMon wrong: %s'%st.bufferMon
    2097
    2098 -def makeStoreCompSuite():
    2099      suite = unittest.TestSuite()
    2100      ## Unmonitored Stores
    2101      testBasicTime  = makeStoreCompTestcase('testBasicTime')
    2102      testBasicEvent = makeStoreCompTestcase('testBasicEvent')
    2103      testBasicTimePut  = makeStoreCompTestcase('testBasicTimePut')
    2104      testBasicEventPut = makeStoreCompTestcase('testBasicEventPut')
    2105      ## Monitored Stores
    2106      testBasicTimePutM = makeStoreCompTestcase('testBasicTimePutM')
    2107      testBasicEventPutM = makeStoreCompTestcase('testBasicEventPutM')
    2108
    2109      suite.addTests([testBasicTime,
    2110                      testBasicEvent,
    2111                      testBasicTimePut,
    2112                      testBasicEventPut,
    2113                      testBasicTimePutM,
    2114                      testBasicEventPutM])
    2115      return suite
    2116
    2117  ## ------------------------------------------------------------------
    2118  ##
    2119  ##  Level: Tests for compound get
    2120  ##
    2121  ## ------------------------------------------------------------------
    2122 -class TBTLev(Process):
    2123      """Level: For testBasicTime"""
    2124 -    def tbt(self, level):
    2125          yield get, self, level, 1
    2126          assert self.got, 'did not get 1 unit'
    2127          yield (get, self, level, 1),(hold, self, 5)
    2128          if self.acquired(level):
    2129              assert self.got == 1, 'did not get 1 unit'
    2130          else:
    2131              assert not self.got and now() == 5, 'time renege not working'
    2132
    2133 -class TBELev(Process):
    2134      """Level: For testBasicEvent"""
    2135 -    def tbe(self, level, trigger):
    2136          yield get, self, level, 1
    2137          assert self.got, 'did not get 1 unit'
    2138          yield (get, self, level, 1),(waitevent, self, trigger)
    2139          if self.acquired(level):
    2140              assert self.got == 1, 'did not get 1 Item'
    2141          else:
    2142              assert now() == 5.5 and self.eventsFired[0] == trigger,\
    2143                     'event renege not working'
    2144
    2145 -class TBEtriggerLev(Process):
    2146      """Level: For testBasicEvent"""
    2147 -    def fire(self, trigger):
    2148          yield hold, self, 5.5
    2149          trigger.signal()
    2150
    2151 -class TBTLevPut(Process):
    2152      """Level: For testBasicTimePut"""
    2153 -    def tbt(self, level):
    2154          yield put, self, level, 1
    2155          assert level.amount, 'did not put 1 unit'
    2156          yield (put, self, level, 1),(hold, self, 5)
    2157          if self.stored(level):
    2158              assert False, 'should have reneged'
    2159          else:
    2160              assert level.amount == 1 and now() == 5, 'time renege not working'
    2161
    2162 -class TBELevPut(Process):
    2163      """Level: For testBasicEventPut and testBasicEventPutM"""
    2164 -    def tbe(self, level, trigger):
    2165          yield (put, self, level, 1),(waitevent, self, trigger)
    2166          if self.stored(level):
    2167              assert level.amount == 1, 'did not put 1 unit'
    2168          else:
    2169              assert False, 'should not have reneged'
    2170          yield (put, self, level, 1),(waitevent, self, trigger)
    2171          if self.stored(level):
    2172              assert False, 'should have reneged'
    2173          else:
    2174              assert now() == 5.5 and self.eventsFired[0] == trigger ,\
    2175                     'renege not working'
    2176
    2177 -class TBEtriggerLevPut(Process):
    2178      """Level: For testBasicEventPut"""
    2179 -    def fire(self, trigger):
    2180          yield hold, self, 5.5
    2181          trigger.signal()
    2182
    2183 -class makeLevelCompTestcase(unittest.TestCase):
    2184      """Level: Testcase for compound get and put statements"""
    2185      ## ------------------------------------------------------------------
    2186      ##             TEST 'yield (get, self, level),(hold, self, time)'
    2187      ##                   == timeout renege
    2188      ##             for both unmonitored and monitored Levels
    2189      ## ------------------------------------------------------------------
    2190
    2191 -    def testBasicTime(self):
    2192          """Level (unmonitored): test 'yield (get, self, level),(hold, self, timeout)"""
    2193          initialize()
    2194          l = Level(initialBuffered = 1)
    2195          t = TBTLev()
    2196          activate(t, t.tbt(level = l))
    2197          simulate(until = 10)
    2198
    2199      ## ------------------------------------------------------------------
    2200      ##             TEST 'yield (put, self, store),(hold, self, time)'
    2201      ##                   == timeout renege
    2202      ##             for both unmonitored and monitored Stores
    2203      ## ------------------------------------------------------------------
    2204 -    def testBasicTimePut(self):
    2205          """Level (unmonitored):
    2206          test 'yield (put, self, level),(hold, self, timeout)"""
    2207          initialize()
    2208          l = Level(capacity = 1)
    2209          t = TBTLevPut()
    2210          activate(t, t.tbt(level = l))
    2211          simulate(until = 10)
    2212
    2213
    2214      ## ------------------------------------------------------------------
    2215      ##             TEST 'yield (get, self, store),(waitevent, self, event)'
    2216      ##                   == event renege
    2217      ##             for both unmonitored and monitored Levels
    2218      ## ------------------------------------------------------------------
    2219 -    def testBasicEvent(self):
    2220          """Level (unmonitored):
    2221          test 'yield (get, self, level),(waitevent, self, event)"""
    2222          initialize()
    2223          l = Level(initialBuffered = 1)
    2224          trig = SimEvent()
    2225          t = TBELev()
    2226          activate(t, t.tbe(level = l, trigger = trig))
    2227          tr = TBEtriggerLev()
    2228          activate(tr, tr.fire(trigger = trig))
    2229          simulate(until = 10)
    2230
    2231 -    def testBasicEventM(self):
    2232          """Level (monitored):
    2233          test monitors with 'yield (get, self, level),(waitevent, self, event)"""
    2234          initialize()
    2235          l = Level(initialBuffered = 1, monitored = True)
    2236          trig = SimEvent()
    2237          t = TBELev()
    2238          activate(t, t.tbe(level = l, trigger = trig))
    2239          tr = TBEtriggerLev()
    2240          activate(tr, tr.fire(trigger = trig))
    2241          simulate(until = 10)
    2242          #First get (t = 0) succeeded and second timed out at t = 5.5?
    2243          assert l.getQMon == [[0, 0],[0, 1],[5.5, 0]],'getQMon not working: %s'\
    2244                                                 %l.getQMon
    2245          #Level amount incr. then decr. by 1 (t = 0), 2nd get reneged at t = 5.5?
    2246          assert l.bufferMon == [[0, 1],[0, 0]],\
    2247                 'bufferMon not working: %s'%l.bufferMon
    2248
    2249      ## ------------------------------------------------------------------
    2250      ##             TEST 'yield (put, self, store),(waitevent, self, event)'
    2251      ##                   == event renege
    2252      ##             for both unmonitored and monitored Levels
    2253      ## ------------------------------------------------------------------
    2254 -    def testBasicEventPut(self):
    2255          """Level (unmonitored):
    2256          test 'yield (put, self, level),(waitevent, self, event)"""
    2257          initialize()
    2258          l = Level(capacity = 1)
    2259          trig = SimEvent()
    2260          t = TBELevPut()
    2261          activate(t, t.tbe(level = l, trigger = trig))
    2262          tr = TBEtriggerLevPut()
    2263          activate(tr, tr.fire(trigger = trig))
    2264          simulate(until = 10)
    2265
    2266 -    def testBasicEventPutM(self):
    2267          """Level (monitored):
    2268          test monitors with 'yield (put, self, level),(waitevent, self, event)"""
    2269          initialize()
    2270          l = Level(capacity = 1, monitored = True)
    2271          trig = SimEvent()
    2272          t = TBELevPut()
    2273          activate(t, t.tbe(level = l, trigger = trig))
    2274          tr = TBEtriggerLevPut()
    2275          activate(tr, tr.fire(trigger = trig))
    2276          simulate(until = 10)
    2277          'First put succeeds, second reneges at t = 5.5?'
    2278          assert l.putQMon == [[0, 0],[0, 1],[5.5, 0]],'putQMon wrong: %s'\
    2279                                                  %l.putQMon
    2280          '1 unit added at t = 0, renege at t = 5 before 2nd unit added?'
    2281          assert l.bufferMon == [[0, 0],[0, 1]],'bufferMon wrong: %s'%l.bufferMon
    2282
    2283 -def makeLevelCompSuite():
    2284      suite = unittest.TestSuite()
    2285      ## Unmonitored Levels
    2286      testBasicTime  = makeLevelCompTestcase('testBasicTime')
    2287      testBasicEvent = makeLevelCompTestcase('testBasicEvent')
    2288      testBasicTimePut = makeLevelCompTestcase('testBasicTimePut')
    2289      testBasicEventPut = makeLevelCompTestcase('testBasicEventPut')
    2290      ## Monitored Levels
    2291      testBasicEventM = makeLevelCompTestcase('testBasicEventM')
    2292      testBasicEventPutM = makeLevelCompTestcase('testBasicEventPutM')
    2293
    2294      suite.addTests([testBasicTime,
    2295                      testBasicEvent,
    2296                      testBasicTimePut,
    2297                      testBasicEventPut,
    2298                      testBasicEventM,
    2299                      testBasicEventPutM])
    2300      return suite
    2301
    2302  if __name__ == '__main__':
    2303      alltests = unittest.TestSuite((makeSSuite(),makeRSuite(),
    2304                                     makeMSuite(),#makeHSuite(),
    2305                                     makeISuite(),makePSuite(),
    2306                                     makeESuite(),makeWSuite(),
    2307                                     makeTOSuite(),makeEvtRenegeSuite(),
    2308                                     makeLevelSuite(),
    2309                                     makeStoreSuite(),
    2310                                     makeStoreCompSuite(),
    2311                                     makeLevelCompSuite()
    2312                                  ))
    2313      runner = unittest.TextTestRunner()
    2314      runner.run(alltests)
    2315