Package SimPy :: Module testSimPyStepOO

[hide private]
[frames] | no frames]

# Source Code for Module SimPy.testSimPyStepOO

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