Package SimPy :: Module testSimPyStepOO |
[hide private]
[frames] | no frames]

# Source Code for Module SimPy.testSimPyStepOO

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