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

# Source Code for Module SimPy.testSimPyRTOO

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