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

# Source Code for Module SimPy.testSimPyOO

       1  #!/usr/bin/env python
       2  from SimPy.Simulation  import *
       3  from SimPy.MonitorTest import *
       4  import unittest
       5  from random import random
       6  # $Revision: 229 $ $Date: 2009-01-26 16:17:21 +0100 (Mo, 26 Jan 2009) $
       7
       8  """testSimPyOO.py
       9  SimPy version 2.0
      10  Unit tests for Simulation.py.
      11
      12  **Change history**:
      13  # 2002 11 15 Added tests for priority queues and preemption
      14  # 2002 11 22 testing problem in accum
      15  # 2003 03 30 added tests for SEP001v17 interrupts
      16  # 2003 04 05 added test for interruptReset
      17  # 2003 04 08 added tests for process state transitions
      18  # 2003 04 10 changed to "self.cancel(victim)" syntax
      19  # 2003 04 13 removed dummy init assertions
      20  # 2004 02 28 added test for monitored queues (gav)
      21  # 2004 05 03 corrected test for monitored queues (gav)
      22  # 2004 09 17 added tests for waitevent, queueevent, waituntil (new in 1.5)
      23  # 2005 05 19 added tests for compound yield statements (reneging)
      24  # 2006 01 15 added tests for Store and Level and the get/put yield statements
      25  # 2006 02 02 removed histogram plotting suite
      26  # 2006 05 10 changed test testStatic for Level to test that float type
      27               supported for initialBuffered
      28  # 2006 05 16 added tests for Store and Level to test basic Producer/Consumer
      29               principles
      30  # 2006 10 16 added tests for compound get statement (Unmonitored Store/Level)
      31  # 2006 10 17 added tests for compound put statement (Unmonitored Store/Level)
      32  # 2007 01 08 added tests for monitoring of Store/Level with compound get/put
      33  # 2007 01 08 added test for Store with filter function
      34  # 2007 12 05 added tests for start method (Process)
      35  # 2008 03 03 added test for nested preempts
      36
      37  # $Revision: 229 $ $Date: 2009-01-26 16:17:21 +0100 (Mo, 26 Jan 2009) $ kgm
      38
      39  """
      40  simulationVersion=version
      41  print "Under test: Simulation.py %s"%simulationVersion
      42  __version__ = '2.0 $Revision: 229 $ $Date: 2009-01-26 16:17:21 +0100 (Mo, 26 Jan 2009) $ '
      43  print "testSimpyOO.py %s"%__version__
      44  ## -------------------------------------------------------------
      45  ##                    TEST SIMULATION
      46  ## -------------------------------------------------------------
      47 -class P(Process):
      48     """ P class for testing"""
      49 -   def __init__(self,name="",T = 0,sim=None):
      50          Process.__init__(self,name,sim)
      51          self.name=name
      52          self.T = T
      53
      54 -   def execute(self):
      55          yield hold,self,self.T
      56
      57 -class PActions(Process):
      58     """ PActions class for testing"""
      59 -   def __init__(self,name="",T = 0,sim=None):
      60          Process.__init__(self,name,sim)
      61          self.name=name
      62          self.T = T
      63
      64 -   def ACTIONS(self):
      65          yield hold,self,self.T
      66
      67 -class makeSimulationtestcase(unittest.TestCase):
      68     """ Tests of simulation
      69     """
      70 -   def testInit(self):
      71          """Test initialisation
      72          """
      73          s=Simulation()
      74          s.initialize()
      75          result=s.simulate(until=10)
      76          assert result=="SimPy: No activities scheduled",\
      77                 "There should have been no activities."
      78          assert(now()==0),"time not 0"
      79
      80 -   def testActivate(self):
      81          """Test activate()
      82          """
      83          s=Simulation()
      84          s.initialize()
      85          P1 = P(name="P1",T=100.0,sim=s)
      86          s.activate(P1,P1.execute(),0)
      87          s.simulate(until=5)
      88          assert(s.now()==5),"Simulate stopped at %s not %s"%(s.now(),5)
      89
      90 -   def testStart(self):
      91         """Test start method
      92         """
      93         s=Simulation()
      94         P1 = P(name="P1",T=100.0,sim=s)
      95         s.initialize()
      96         P1.start(P1.execute(),0)
      97         s.simulate(until=5)
      98         assert(s.now()==5),"Simulate stopped at %s not %s"%(now(),5)
      99
     100 -   def testStartActions(self):
     101        """Test start method with ACTIONS PEM
     102        """
     103        s=Simulation()
     104        P1 = PActions(name="P1",T=100.0,sim=s)
     105        s.initialize()
     106        P1.start()
     107        s.simulate(until=5)
     108        assert(s.now()==5),"Simulate stopped at %s not %s"%(s.now(),5)
     109
     110 -   def testYield(self):
     111          """Test yield hold and simulate(until)
     112          """
     113          s=Simulation()
     114          s.initialize()
     115          P1 = P(name="P1",T=10,sim=s)
     116          s.initialize()
     117          s.activate(P1,P1.execute(),0)
     118          s.simulate(until=5)
     119          assert(s.now()==5),"Simulate stopped at %s not %s"%(s.now(),5)
     120          ## should stop at 0 for next event is at 10s
     121          P2 = P(name="P2",T=10,sim=s)
     122          s.initialize()
     123          s.activate(P2,P2.execute(),0)
     124          s.simulate(until=20)
     125          assert(s.now()==10),"P1 hold to %s not %s"%(s.now(),10)
     126
     127 -def makeSSuite():
     128      suite = unittest.TestSuite()
     129      testInit = makeSimulationtestcase("testInit")
     130      testActivate = makeSimulationtestcase("testActivate")
     131      testStart=makeSimulationtestcase("testStart")
     132      testStartActions=makeSimulationtestcase("testStartActions")
     133      testYield = makeSimulationtestcase("testYield")
     134      suite.addTests([testInit,testActivate,testStart,testStartActions,
     135                      testYield])
     136      return suite
     137
     138  ## -------------------------------------------------------------
     139  ##                    TEST RESOURCES
     140  ## -------------------------------------------------------------
     141
     142 -class Job(Process):
     143     """ Job class for testing"""
     144 -   def __init__(self,server=None,name="",sim=None):
     145          Process.__init__(self,name,sim)
     146          self.name=name
     147          self.R=server
     148
     149 -   def execute(self):
     150          yield request,self,self.R
     151
     152 -class makeResourcetestcase(unittest.TestCase):
     153     """ First simple tests of Resources
     154     """
     155 -   def testInit(self):
     156          """Test initialisation"""
     157          s=Simulation()
     158          s.initialize()
     159          R = Resource(sim=s)
     160          assert R.name == "a_resource", "Not null name"
     161          assert R.capacity == 1, "Not unit capacity"
     162          assert R.unitName =="units", "Not the correct unit name"
     163          R = Resource(name='',capacity=1,sim=s)
     164          assert R.name == "", "Not null name"
     165          assert R.capacity == 1, "Not unit capacity"
     166          assert R.unitName =="units", "Not the correct unit name"
     167          R = Resource(capacity=3,name="3-version",unitName="blobs",sim=s)
     168          assert R.name =="3-version" , "Wrong name, it is"+R.name
     169          assert R.capacity == 3, "Not capacity 3, it is "+`R.capacity`
     170          assert R.unitName =="blobs", "Not the correct unit name"
     171          ## next test 0 capacity is allowed
     172          R = Resource(capacity=0,name="0-version",sim=s)
     173          assert R.capacity ==0, "Not capacity 0, it is "+`R.capacity`
     174
     175 -   def testrequest(self):
     176          """Test request"""
     177          ## NB this next call should be changed to
     178          ## R = Resource() when Simulation is fixed
     179          R0 = Resource(name='',capacity=0)
     180          assert R0.name == "", "Not null name"
     181          assert R0.capacity == 0, "Not capacity 0, it is "+`R0.capacity`
     182          ## now test requesting: ------------------------------------
     183          s=Simulation()
     184          s.initialize()
     185          R1 = Resource(capacity=0,name="3-version",unitName="blobs")
     186          J= Job(name="job",server=R1)
     187          s.activate(J,J.execute(), at=0.0) # this requests a unit of R1
     188          ## when simulation starts
     189          s.simulate(until=10.0)
     190          assert R1.n == 0 , "Should be 0, it is "+str(R1.n)
     191          lenW = len(R1.waitQ)
     192          assert lenW==1,"Should be 1, it is "+str(lenW)
     193          assert len(R1.activeQ)==0,"len activeQ Should be 0, it is "+\
     194          str(len(R1.activeQ))
     195
     196 -   def testrequest2(self):
     197          """Test request2 with capacity = 1"""
     198          ## now test requesting: ------------------------------------
     199          s=Simulation()
     200          s.initialize()
     201          R2 = Resource(capacity=1,name="3-version",unitName="blobs")
     202          J2= Job(name="job",server=R2)
     203          s.activate(J2,J2.execute(), at=0.0) # requests a unit of R2
     204          ## when simulation starts
     205          s.simulate(until = 10.0)
     206          assert R2.n == 0 , "Should be 0, it is "+str(R2.n)
     207          lenW = len(R2.waitQ)
     208          lenA = len(R2.activeQ)
     209          assert lenW==0,"lenW Should be 0, it is "+str(lenW)
     210          assert lenA==1,"lenA Should be 1, it is "+str(lenA)
     211
     212 -   def testrequest3(self):
     213          """Test request3 with capacity = 1 several requests"""
     214          ## now test requesting: ------------------------------------
     215          s=Simulation()
     216          s.initialize()
     217          R3 = Resource(capacity=1,name="3-version",unitName="blobs")
     218          J2= Job(name="job",server=R3)
     219          J3= Job(name="job",server=R3)
     220          J4= Job(name="job",server=R3)
     221          s.activate(J2,J2.execute(), at=0.0) # requests a unit of R3
     222          s.activate(J3,J3.execute(), at=0.0) # requests a unit of R3
     223          s.activate(J4,J4.execute(), at=0.0) # requests a unit of R3
     224          ## when simulation starts
     225          s.simulate(until = 10.0)
     226          assert R3.n == 0 , "Should be 0, it is "+str(R3.n)
     227          lenW = len(R3.waitQ)
     228          lenA = len(R3.activeQ)
     229          assert lenW==2,"lenW Should be 2, it is "+str(lenW)
     230          assert R3.waitQ==[J3,J4],"WaitQ wrong"+str(R3.waitQ)
     231          assert lenA==1,"lenA Should be 1, it is "+str(lenA)
     232          assert R3.activeQ==[J2],"activeQ wrong, it is %s"%str(R3.activeQ[0])
     233
     234 -   def testrequest4(self):
     235          """Test request4 with capacity = 2 several requests"""
     236          ## now test requesting: ------------------------------------
     237          s=Simulation()
     238          s.initialize()
     239          R3 = Resource(capacity=2,name="4-version",unitName="blobs")
     240          J2= Job(name="job",server=R3)
     241          J3= Job(name="job",server=R3)
     242          J4= Job(name="job",server=R3)
     243          s.activate(J2,J2.execute(), at=0.0) # requests a unit of R3
     244          s.activate(J3,J3.execute(), at=0.0) # requests a unit of R3
     245          s.activate(J4,J4.execute(), at=0.0) # requests a unit of R3
     246          ## when simulation starts
     247          s.simulate(until = 10.0)
     248          assert R3.n == 0 , "Should be 0, it is "+str(R3.n)
     249          lenW = len(R3.waitQ)
     250          lenA = len(R3.activeQ)
     251          assert lenW==1,"lenW Should be 1, it is "+str(lenW)
     252          assert R3.waitQ==[J4],"WaitQ wrong"+str(R3.waitQ)
     253          assert lenA==2,"lenA Should be 2, it is "+str(lenA)
     254          assert R3.activeQ==[J2,J3],"activeQ wrong, it is %s"%str(R3.activeQ[0])
     255  ##
     256  #------- Test Priority Queues
     257  ##
     258 -   def testrequestPriority(self):
     259          """Test PriorityQ, with no preemption, 0 capacity"""
     260          class Job(Process):
     261             """ Job class for testing"""
     262             def __init__(self,server=None,name="",sim=None):
     263                Process.__init__(self,name,sim)
     264                self.name=name
     265                self.R=server
     266
     267             def execute(self,priority):
     268                yield request,self,self.R,priority
     269
     270          s=Simulation()
     271          s.initialize()
     272          Rp = Resource(capacity=0,qType=PriorityQ,sim=s)
     273          J5 = Job(name="job 5",server=Rp,sim=s)
     274          J6 = Job(name="job 6",server=Rp,sim=s)
     275          J7 = Job(name="job 7",server=Rp,sim=s)
     276          s.activate(J5,J5.execute(priority=3))
     277          s.activate(J6,J6.execute(priority=0))
     278          s.activate(J7,J7.execute(priority=1))
     279          s.simulate(until=100)
     280          assert Rp.waitQ == [J5,J7,J6],"WaitQ wrong: %s"\
     281                                 %str([(x.name,x.priority[Rp]) for x in Rp.waitQ])
     282
     283          """Test PriorityQ mechanism"""
     284
     285          def sorted(q):
     286             if not q or len(q) == 1:
     287                sortok=1
     288                return sortok
     289             sortok = q[0] >= q[1] and sorted(q[2:])
     290             return sortok
     291
     292          s=Simulation()
     293          s.initialize()
     294          Rp=Resource(capacity=0,qType=PriorityQ,sim=s)
     295          for i in range(10):
     296             J=Job(name="job "+str(i),server=Rp,sim=s)
     297             s.activate(J,J.execute(priority=random()))
     298          s.simulate(until=1000)
     299          qp=[x._priority[Rp] for x in Rp.waitQ]
     300          assert sorted(qp),"waitQ not sorted by priority: %s"\
     301                             %str([(x.name,x._priority[Rp]) for x in Rp.waitQ])
     302
     303 -   def testrequestPriority1(self):
     304          """Test PriorityQ, with no preemption, capacity == 1"""
     305          class Job(Process):
     306             """ Job class for testing"""
     307             def __init__(self,server=None,name="",sim=None):
     308                Process.__init__(self,name,sim)
     309                self.name=name
     310                self.R=server
     311
     312             def execute(self,priority):
     313                yield request,self,self.R,priority
     314
     315          s=Simulation()
     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,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.nameself.sim.now())
     351               yield release,self,res
     352
     353         s = Simulation()
     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,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=Simulation()
     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=Simulation()
     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,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=Simulation()
     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=Simulation()
     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=Simulation()
     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=Simulation()
     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=Simulation()
     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=Simulation()
     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 noit 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=Simulation()
     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=Simulation()
     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=Simulation()
     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=Simulation()
     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=Simulation()
     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=Simulation()
     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=Simulation()
     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()
     895        e1.signal()
     896        e2=SimEvent()
     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()
     919          e1.signal()
     920          e2=SimEvent()
     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=Simulation()
     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=Simulation()
     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  ##      initialize()
     968  ##      e1=SimEvent("e1")
     969  ##      e2=SimEvent("e2")
     970  ##      e3=SimEvent("e3")
     971  ##      s=SignalProcessOR()
     972  ##      activate(s,s.makeSignal(e1,e3))
     973  ##      w=WaitProcessOR()
     974  ##      activate(w,w.waitForSig([e1,e2]))
     975  ##      for i in range(5):
     976  ##         q=QueueProcessOR()
     977  ##         activate(q,q.queueForSig([e2,e3]))
     978  ##      simulate(until=10)
     979
     980 -   def testSimEvents3(self):
     981        """
     982        Tests waiting, queuing for at least one event out of a list/tuple.
     983        """
     984        si=Simulation()
     985        si.initialize()
     986        e1=SimEvent("e1",sim=si)
     987        e2=SimEvent("e2",sim=si)
     988        e3=SimEvent("e3",sim=si)
     989        s=SignalProcessOR(sim=si)
     990        si.activate(s,s.makeSignal(e1,e3))
     991        w=WaitProcessOR(sim=si)
     992        si.activate(w,w.waitForSig([e1,e2]))
     993        for i in range(5):
     994           q=QueueProcessOR(sim=si)
     995           si.activate(q,q.queueForSig([e2,e3]))
     996        si.simulate(until=10)
     997
     998 -   def testSimEvents4(self):
     999        """Tests that eventsFired reports all events which fired
    1000        """
    1001        s=Simulation()
    1002        s.initialize()
    1003        w=WaitProcessOR1(sim=s)
    1004        s.activate(w,w.signalandwait())
    1005        s.simulate(until=5)
    1006
    1007 -   def testSimEvents5(self):
    1008        """Tests that eventsFired reports all events which fired
    1009        """
    1010        s=Simulation()
    1011        s.initialize()
    1012        w=QueueProcessOR1(sim=s)
    1013        s.activate(w,w.signalandqueue())
    1014        s.simulate(until=5)
    1015
    1016 -def makeESuite():
    1017     suite=unittest.TestSuite()
    1018     testSimEvents1=makeEtestcase("testSimEvents1")
    1019     testSimEvents2=makeEtestcase("testSimEvents2")
    1020     testSimEvents3=makeEtestcase("testSimEvents3")
    1021     testSimEvents4=makeEtestcase("testSimEvents4")
    1022     testSimEvents5=makeEtestcase("testSimEvents5")
    1023     suite.addTests([testSimEvents1,testSimEvents2,testSimEvents3,
    1024                     testSimEvents4,testSimEvents5])
    1025     return suite
    1026
    1027  ## -------------------------------------------------------------
    1028  ##                    TEST waituntil
    1029  ## -------------------------------------------------------------
    1030
    1031 -class Signaller(Process):
    1032 -    def __init__(self,sim=None):
    1033          Process.__init__(self,sim=sim)
    1034 -    def makeconditions(self,waiter):
    1035          global a,b,c
    1036          a=True
    1037          yield hold,self,1
    1038          b=True
    1039          yield hold,self,1
    1040          c=True
    1041          yield hold,self,1
    1042          assert waiter.terminated(),"waituntil did not fire"
    1043
    1044 -class Waiter(Process):
    1045 -    def __init__(self,sim=None):
    1046          Process.__init__(self,sim=sim)
    1047 -    def waitforit(self):
    1048          def waitcond():
    1049              return a and b and c
    1050          yield waituntil,self,waitcond
    1051
    1052 -class makeWtestcase(unittest.TestCase):
    1053     """
    1054     Test waituntil as introduced with SimPy 1.5
    1055     """
    1056
    1057 -   def testwaituntil1(self):
    1058         global a,b,c
    1059         a=b=c=False
    1060         si=Simulation()
    1061         si.initialize()
    1062         w=Waiter(sim=si)
    1063         si.activate(w,w.waitforit())
    1064         s=Signaller(sim=si)
    1065         si.activate(s,s.makeconditions(w))
    1066         si.simulate(until=5)
    1067
    1068 -def makeWSuite():
    1069     suite=unittest.TestSuite()
    1070     testwaituntil1=makeWtestcase("testwaituntil1")
    1071     suite.addTests([testwaituntil1])
    1072     return suite
    1073
    1074  ## -------------------------------------------------------------
    1075  ##                    TEST COMPOUND "YIELD REQUEST" COMMANDS
    1076  ## -------------------------------------------------------------
    1077
    1078  ## -------------------------------------------------------------
    1079  ##             TEST "yield (request,self,res),(hold,self,delay)"
    1080  ##                   == timeout renege
    1081  ##             for both unmonitored and monitored resources
    1082  ## -------------------------------------------------------------
    1083
    1084 -class JobTO(Process):
    1085     """ Job class for testing timeout reneging
    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):
    1093          yield (request,self,self.res),(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 JobTO_P(Process):
    1102     """ Job class for testing timeout reneging with priorities
    1103     """
    1104 -   def __init__(self,server=None,name="",sim=None):
    1105          Process.__init__(self,name=name,sim=sim)
    1106          self.res=server
    1107          self.gotResource=None
    1108
    1109 -   def execute(self,timeout,usetime,priority):
    1110          yield (request,self,self.res,priority),(hold,self,timeout)
    1111          if self.acquired(self.res):
    1112              self.gotResource=True
    1113              yield hold,self,usetime
    1114              yield release,self,self.res
    1115          else:
    1116              self.gotResource=False
    1117
    1118 -class makeTimeoutTestcase(unittest.TestCase):
    1119      """ Tests of "yield (request,self,res),(hold,self,delay)"
    1120          timeout reneging command
    1121      """
    1122 -    def testNoTimeout(self):
    1123          """Test that resource gets acquired without timeout
    1124          """
    1125
    1126          s=Simulation()
    1127          s.initialize()
    1128          res=Resource(name="Server",capacity=1,sim=s)
    1129          usetime=5
    1130          timeout=1000000
    1131          j1=JobTO(server=res,name="Job_1",sim=s)
    1132          s.activate(j1,j1.execute(timeout=timeout,usetime=usetime))
    1133          j2=JobTO(server=res,name="Job_2",sim=s)
    1134          s.activate(j2,j2.execute(timeout=timeout,usetime=usetime))
    1135          s.simulate(until=2*usetime)
    1136          assert s.now()==2*usetime,"time not ==2*usetime"
    1137          assert j1.gotResource and j2.gotResource,\
    1138              "at least one job failed to get resource"
    1139          assert not (res.waitQ or res.activeQ),\
    1140              "job waiting or using resource"
    1141
    1142 -    def testNoTimeoutM(self):
    1143          """Test that resource gets acquired without timeout.
    1144             Resource monitored.
    1145          """
    1146
    1147          s=Simulation()
    1148          s.initialize()
    1149          res=Resource(name="Server",capacity=1,monitored=True,sim=s)
    1150          usetime=5
    1151          timeout=1000000
    1152          j1=JobTO(server=res,name="Job_1",sim=s)
    1153          s.activate(j1,j1.execute(timeout=timeout,usetime=usetime))
    1154          j2=JobTO(server=res,name="Job_2",sim=s)
    1155          s.activate(j2,j2.execute(timeout=timeout,usetime=usetime))
    1156          s.simulate(until=2*usetime)
    1157          assert s.now()==2*usetime,"time not ==2*usetime"
    1158          assert j1.gotResource and j2.gotResource,\
    1159              "at least one job failed to get resource"
    1160          assert not (res.waitQ or res.activeQ),\
    1161              "job waiting or using resource"
    1162          assert res.waitMon==[[0,1],[usetime,0]],"res.waitMon wrong: %s"%res.waitMon
    1163
    1164 -    def testTimeout1(self):
    1165          """Test that timeout occurs when resource busy
    1166          """
    1167
    1168          s=Simulation()
    1169          s.initialize()
    1170          res=Resource(name="Server",capacity=1,sim=s)
    1171          usetime=5
    1172          timeout=3
    1173          j1=JobTO(server=res,name="Job_1",sim=s)
    1174          s.activate(j1,j1.execute(timeout=timeout,usetime=usetime))
    1175          j2=JobTO(server=res,name="Job_2",sim=s)
    1176          s.activate(j2,j2.execute(timeout=timeout,usetime=usetime))
    1177          s.simulate(until=2*usetime)
    1178          assert(s.now()==usetime),"time not ==usetime"
    1179          assert(j1.gotResource),"Job_1 did not get resource"
    1180          assert(not j2.gotResource),"Job_2 did not renege"
    1181          assert not (res.waitQ or res.activeQ),\
    1182              "job waiting or using resource"
    1183
    1184 -    def testTimeout1M(self):
    1185          """Test that timeout occurs when resource busy.
    1186             Resource monitored.
    1187          """
    1188          s=Simulation()
    1189          s.initialize()
    1190          res=Resource(name="Server",capacity=1,monitored=True,sim=s)
    1191          usetime=5
    1192          timeout=3
    1193          j1=JobTO(server=res,name="Job_1",sim=s)
    1194          s.activate(j1,j1.execute(timeout=timeout,usetime=usetime))
    1195          j2=JobTO(server=res,name="Job_2",sim=s)
    1196          s.activate(j2,j2.execute(timeout=timeout,usetime=usetime))
    1197          s.simulate(until=2*usetime)
    1198          assert(s.now()==usetime),"time not == usetime"
    1199          assert(j1.gotResource),"Job_1 did not get resource"
    1200          assert(not j2.gotResource),"Job_2 did not renege"
    1201          assert not (res.waitQ or res.activeQ),\
    1202              "job waiting or using resource"
    1203          assert res.waitMon==[[0,1],[timeout,0]],"res.waitMon wrong: %s"%res.waitMon
    1204
    1205 -    def testTimeout_MP(self):
    1206          """Test that timeout occurs when resource busy.
    1207             Resource monitored. Requests with priority and preemption.
    1208          """
    1209          s=Simulation()
    1210          s.initialize()
    1211          res=Resource(name="Server",capacity=1,monitored=True,
    1212                       qType=PriorityQ,preemptable=True,sim=s)
    1213          usetime=5
    1214          timeout=3
    1215          j1=JobTO_P(server=res,name="Job_1",sim=s)
    1216          s.activate(j1,j1.execute(timeout=timeout,usetime=usetime,priority=1))
    1217          j2=JobTO_P(server=res,name="Job_2",sim=s)
    1218          j2_arrival=1
    1219          s.activate(j2,j2.execute(timeout=timeout,usetime=usetime,priority=5),
    1220                     at=j2_arrival)
    1221          j3=JobTO_P(server=res,name="Job_2",sim=s)
    1222          j3_arrival=2
    1223          s.activate(j3,j3.execute(timeout=timeout,usetime=usetime,priority=10),
    1224                     at=j3_arrival)
    1225          s.simulate(until=3*usetime)
    1226          assert(s.now()== 3*usetime),"time not == 2* usetime, but %s"%now()
    1227          assert(j1.gotResource),"Job_1 did not get resource"
    1228          assert(j2.gotResource),"Job_2 did renege"
    1229          assert(j2.gotResource),"Job_3 did renege"
    1230          assert not (res.waitQ or res.activeQ),\
    1231              "job waiting or using resource"
    1232          assert res.waitMon==[[j2_arrival,1],[j3_arrival,2],[usetime+j3_arrival,1],[usetime+j2_arrival+usetime,0]],\
    1233               "res.waitMon wrong: %s"%res.waitMon
    1234
    1235 -    def testTimeout2(self):
    1236          """Test that timeout occurs when resource has no capacity free
    1237          """
    1238
    1239          s=Simulation()
    1240          s.initialize()
    1241          res=Resource(name="Server",capacity=0,sim=s)
    1242          usetime=5
    1243          timeout=3
    1244          j1=JobTO(server=res,name="Job_1",sim=s)
    1245          s.activate(j1,j1.execute(timeout=timeout,usetime=usetime))
    1246          j2=JobTO(server=res,name="Job_2",sim=s)
    1247          s.activate(j2,j2.execute(timeout=timeout,usetime=usetime))
    1248          s.simulate(until=2*usetime)
    1249          assert s.now()==timeout,"time %s not == timeout"%now()
    1250          assert not j1.gotResource,"Job_1 got resource"
    1251          assert not j2.gotResource,"Job_2 got resource"
    1252          assert not (res.waitQ or res.activeQ),\
    1253                 "job waiting or using resource"
    1254
    1255 -    def testTimeout2M(self):
    1256          """Test that timeout occurs when resource has no capacity free.
    1257             Resource monitored.
    1258          """
    1259
    1260          s=Simulation()
    1261          s.initialize()
    1262          res=Resource(name="Server",capacity=0,monitored=True,sim=s)
    1263          usetime=5
    1264          timeout=3
    1265          j1=JobTO(server=res,name="Job_1",sim=s)
    1266          s.activate(j1,j1.execute(timeout=timeout,usetime=usetime))
    1267          j2=JobTO(server=res,name="Job_2",sim=s)
    1268          s.activate(j2,j2.execute(timeout=timeout,usetime=usetime))
    1269          s.simulate(until=2*usetime)
    1270          assert s.now()==timeout,"time %s not == timeout"%now()
    1271          assert not j1.gotResource,"Job_1 got resource"
    1272          assert not j2.gotResource,"Job_2 got resource"
    1273          assert not (res.waitQ or res.activeQ),\
    1274              "job waiting or using resource"
    1275          assert res.waitMon==[[0,1],[0,2],[timeout,1],[timeout,0]],\
    1276              "res.waitMon is wrong: %s"%res.waitMon
    1277
    1278 -def makeTOSuite():
    1279      suite = unittest.TestSuite()
    1280      testNoTimeout = makeTimeoutTestcase("testNoTimeout")
    1281      testNoTimeoutM = makeTimeoutTestcase("testNoTimeoutM")
    1282      testTimeout1=makeTimeoutTestcase("testTimeout1")
    1283      testTimeout1M=makeTimeoutTestcase("testTimeout1M")
    1284      testTimeout_MP=makeTimeoutTestcase("testTimeout_MP")
    1285      testTimeout2=makeTimeoutTestcase("testTimeout2")
    1286      testTimeout2M=makeTimeoutTestcase("testTimeout2M")
    1287      suite.addTests([testNoTimeout,testNoTimeoutM,testTimeout1,
    1288                      testTimeout1M,testTimeout_MP,testTimeout2,
    1289                      testTimeout2M])
    1290      return suite
    1291
    1292  ## ------------------------------------------------------------------
    1293  ##             TEST "yield (request,self,res),(waitevent,self,event)"
    1294  ##                   == event renege
    1295  ##             for both unmonitored and monitored resources
    1296  ## ------------------------------------------------------------------
    1297
    1298
    1299 -class JobEvt(Process):
    1300     """ Job class for testing event reneging
    1301     """
    1302 -   def __init__(self,server=None,name="",sim=None):
    1303          Process.__init__(self,name,sim=sim)
    1304          self.res=server
    1305          self.gotResource=None
    1306
    1307 -   def execute(self,event,usetime):
    1308          yield (request,self,self.res),(waitevent,self,event)
    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 JobEvtMulti(Process):
    1317     """ Job class for testing event reneging with multi-event lists
    1318     """
    1319 -   def __init__(self,server=None,name="",sim=None):
    1320          Process.__init__(self,name,sim=sim)
    1321          self.res=server
    1322          self.gotResource=None
    1323
    1324 -   def execute(self,eventlist,usetime):
    1325          yield (request,self,self.res),(waitevent,self,eventlist)
    1326          if self.acquired(self.res):
    1327              self.gotResource=True
    1328              yield hold,self,usetime
    1329              yield release,self,self.res
    1330          else:
    1331              self.gotResource=False
    1332
    1333 -class FireEvent(Process):
    1334      """Fires reneging event
    1335      """
    1336 -    def __init__(self,name="",sim=None):
    1337          Process.__init__(self,name,sim=sim)
    1338 -    def fire(self,fireDelay,event):
    1339          yield hold,self,fireDelay
    1340          event.signal()
    1341
    1342 -class makeEventRenegeTestcase(unittest.TestCase):
    1343      """Tests of "yield (request,self,res),(waiteevent,self,event)"
    1344         event reneging command
    1345      """
    1346 -    def testNoEvent(self):
    1347          """Test that processes acquire resource normally if no event fires
    1348          """
    1349          s=Simulation()
    1350          s.initialize()
    1351          event=SimEvent("Renege_trigger",sim=s) #never gets fired
    1352          res=Resource(name="Server",capacity=1,sim=s)
    1353          usetime=5
    1354          j1=JobEvt(server=res,name="Job_1",sim=s)
    1355          s.activate(j1,j1.execute(event=event,usetime=usetime))
    1356          j2=JobEvt(server=res,name="Job_2",sim=s)
    1357          s.activate(j2,j2.execute(event=event,usetime=usetime))
    1358          s.simulate(until=2*usetime)
    1359          # Both jobs should get server (in sequence)
    1360          assert s.now()==2*usetime,"time not ==2*usetime"
    1361          assert j1.gotResource and j2.gotResource,\
    1362              "at least one job failed to get resource"
    1363          assert not (res.waitQ or res.activeQ),\
    1364              "job waiting or using resource"
    1365
    1366 -    def testNoEventM(self):
    1367          """Test that processes acquire resource normally if no event fires.
    1368             Resource monitored.
    1369          """
    1370          s=Simulation()
    1371          s.initialize()
    1372          res=Resource(name="Server",capacity=1,monitored=True,sim=s)
    1373          event=SimEvent("Renege_trigger",sim=s) #never gets fired
    1374          usetime=5
    1375          j1=JobEvt(server=res,name="Job_1",sim=s)
    1376          s.activate(j1,j1.execute(event=event,usetime=usetime))
    1377          j2=JobEvt(server=res,name="Job_2",sim=s)
    1378          s.activate(j2,j2.execute(event=event,usetime=usetime))
    1379          s.simulate(until=2*usetime)
    1380          # Both jobs should get server (in sequence)
    1381          assert s.now()==2*usetime,"time not ==2*usetime"
    1382          assert j1.gotResource and j2.gotResource,\
    1383              "at least one job failed to get resource"
    1384          assert not (res.waitQ or res.activeQ),\
    1385              "job waiting or using resource"
    1386          assert res.waitMon==[[0,1],[usetime,0]],"res.waitMoni is wrong: %s"%res.waitMon
    1387
    1388 -    def testWaitEvent1(self):
    1389          """Test that signalled event leads to renege when resource busy
    1390          """
    1391
    1392          s=Simulation()
    1393          s.initialize()
    1394          res=Resource(name="Server",capacity=1,sim=s)
    1395          event=SimEvent("Renege_trigger",sim=s)
    1396          usetime=5
    1397          eventtime=1
    1398          j1=JobEvt(server=res,name="Job_1",sim=s)
    1399          s.activate(j1,j1.execute(event=event,usetime=usetime))
    1400          j2=JobEvt(server=res,name="Job_2",sim=s)
    1401          s.activate(j2,j2.execute(event=event,usetime=usetime))
    1402          f=FireEvent(name="FireEvent",sim=s)
    1403          s.activate(f,f.fire(fireDelay=eventtime,event=event))
    1404          s.simulate(until=2*usetime)
    1405          # Job_1 should get server, Job_2 renege
    1406          assert(s.now()==usetime),"time not ==usetime"
    1407          assert(j1.gotResource),"Job_1 did not get resource"
    1408          assert(not j2.gotResource),"Job_2 did not renege"
    1409          assert not (res.waitQ or res.activeQ),\
    1410              "job waiting or using resource"
    1411
    1412 -    def testWaitEvent1M(self):
    1413          """Test that signalled event leads to renege when resource busy.
    1414             Resource monitored.
    1415          """
    1416
    1417          s=Simulation()
    1418          s.initialize()
    1419          res=Resource(name="Server",capacity=1,monitored=True,sim=s)
    1420          event=SimEvent("Renege_trigger",sim=s)
    1421          usetime=5
    1422          eventtime=1
    1423          j1=JobEvt(server=res,name="Job_1",sim=s)
    1424          s.activate(j1,j1.execute(event=event,usetime=usetime))
    1425          j2=JobEvt(server=res,name="Job_2",sim=s)
    1426          s.activate(j2,j2.execute(event=event,usetime=usetime))
    1427          f=FireEvent(name="FireEvent",sim=s)
    1428          s.activate(f,f.fire(fireDelay=eventtime,event=event))
    1429          s.simulate(until=2*usetime)
    1430          # Job_1 should get server, Job_2 renege
    1431          assert(s.now()==usetime),"time not ==usetime"
    1432          assert(j1.gotResource),"Job_1 did not get resource"
    1433          assert(not j2.gotResource),"Job_2 did not renege"
    1434          assert not (res.waitQ or res.activeQ),\
    1435              "job waiting or using resource"
    1436          assert res.waitMon==[[0,1],[eventtime,0]],"res.waitMon is wrong: %s"%res.waitMon
    1437
    1438 -    def testWaitEvent2(self):
    1439          """Test that renege-triggering event can be one of an event list
    1440          """
    1441
    1442          s=Simulation()
    1443          s.initialize()
    1444          res=Resource(name="Server",capacity=1,sim=s)
    1445          event1=SimEvent("Renege_trigger_1",sim=s)
    1446          event2=SimEvent("Renege_trigger_2",sim=s)
    1447          usetime=5
    1448          eventtime=1 #for both events
    1449          j1=JobEvtMulti(server=res,name="Job_1",sim=s)
    1450          s.activate(j1,j1.execute(eventlist=[event1,event2],usetime=usetime))
    1451          j2=JobEvtMulti(server=res,name="Job_2",sim=s)
    1452          s.activate(j2,j2.execute(eventlist=[event1,event2],usetime=usetime))
    1453          f1=FireEvent(name="FireEvent_1",sim=s)
    1454          s.activate(f1,f1.fire(fireDelay=eventtime,event=event1))
    1455          f2=FireEvent(name="FireEvent_2",sim=s)
    1456          s.activate(f2,f2.fire(fireDelay=eventtime,event=event2))
    1457          s.simulate(until=2*usetime)
    1458          # Job_1 should get server, Job_2 should renege
    1459          assert(s.now()==usetime),"time not ==usetime"
    1460          assert(j1.gotResource),"Job_1 did not get resource"
    1461          assert(not j2.gotResource),"Job_2 did not renege"
    1462          assert not (res.waitQ or res.activeQ),\
    1463              "job waiting or using resource"
    1464
    1465 -    def testWaitEvent2M(self):
    1466          """Test that renege-triggering event can be one of an event list.
    1467             Resource monitored.
    1468          """
    1469
    1470          s=Simulation()
    1471          s.initialize()
    1472          res=Resource(name="Server",capacity=1,monitored=True,sim=s)
    1473          event1=SimEvent("Renege_trigger_1",sim=s)
    1474          event2=SimEvent("Renege_trigger_2",sim=s)
    1475          usetime=5
    1476          eventtime=1 #for both events
    1477          j1=JobEvtMulti(server=res,name="Job_1",sim=s)
    1478          s.activate(j1,j1.execute(eventlist=[event1,event2],usetime=usetime))
    1479          j2=JobEvtMulti(server=res,name="Job_2",sim=s)
    1480          s.activate(j2,j2.execute(eventlist=[event1,event2],usetime=usetime))
    1481          f1=FireEvent(name="FireEvent_1",sim=s)
    1482          s.activate(f1,f1.fire(fireDelay=eventtime,event=event1))
    1483          f2=FireEvent(name="FireEvent_2",sim=s)
    1484          s.activate(f2,f2.fire(fireDelay=eventtime,event=event2))
    1485          s.simulate(until=2*usetime)
    1486          # Job_1 should get server, Job_2 should renege
    1487          assert(s.now()==usetime),"time not ==usetime"
    1488          assert(j1.gotResource),"Job_1 did not get resource"
    1489          assert(not j2.gotResource),"Job_2 did not renege"
    1490          assert not (res.waitQ or res.activeQ),\
    1491              "job waiting or using resource"
    1492          assert res.waitMon==[[0,1],[eventtime,0]],"res.waitMon is wrong: %s"%res.waitMon
    1493
    1494 -def makeEvtRenegeSuite():
    1495      suite = unittest.TestSuite()
    1496      testNoEvent = makeEventRenegeTestcase("testNoEvent")
    1497      testNoEventM = makeEventRenegeTestcase("testNoEventM")
    1498      testWaitEvent1=makeEventRenegeTestcase("testWaitEvent1")
    1499      testWaitEvent1M=makeEventRenegeTestcase("testWaitEvent1M")
    1500      testWaitEvent2=makeEventRenegeTestcase("testWaitEvent2")
    1501      testWaitEvent2M=makeEventRenegeTestcase("testWaitEvent2M")
    1502
    1503      suite.addTests([testNoEvent,testNoEventM,testWaitEvent1,
    1504                      testWaitEvent1M,testWaitEvent2,testWaitEvent2M])
    1505      return suite
    1506
    1507  ## ------------------------------------------------------------------
    1508  ##             TEST "yield get,self,level,whatToGet" and
    1509  ##                  "yield put,self,level,whatToPut,priority"
    1510  ##             for Level instances
    1511  ## ------------------------------------------------------------------
    1512 -class Producer(Process):
    1513      produced=0
    1514 -    def __init__(self,name="",sim=None):
    1515          Process.__init__(self,name=name,sim=sim)
    1516 -    def produce(self,buffer):
    1517          for i in range(4):
    1518              Producer.produced+=1
    1519              yield put,self,buffer
    1520              yield hold,self,1
    1521 -    def producePriority(self,buffer,priority):
    1522          """PriorityQ for Producers"""
    1523          Producer.produced+=4
    1524          yield put,self,buffer,4,priority
    1525          yield hold,self,1
    1526          self.done=self.sim.now()
    1527          doneList.append(self.name)
    1528 -    def produce1(self,buffer):
    1529          for i in range(4):
    1530              yield put,self,buffer,4
    1531              yield hold,self,1
    1532 -class Consumer(Process):
    1533      consumed=0
    1534 -    def __init__(self,name="",sim=None):
    1535          Process.__init__(self,name=name,sim=sim)
    1536 -    def consume(self,buffer):
    1537          """FIFO"""
    1538          yield get,self,buffer
    1539          Consumer.consumed+=1
    1540          assert self.got==1,"wrong self.got: %s"%self.got
    1541          yield get,self,buffer,3
    1542          Consumer.consumed+=3
    1543          assert self.got==3,"wrong self.got: %s"%self.got
    1544
    1545 -    def consume1(self,buffer):
    1546          """producer PriorityQ, consumer FIFO"""
    1547          while True:
    1548              yield get,self,buffer,2
    1549              yield hold,self,1
    1550 -    def consumePriority(self,buffer,priority):
    1551          """PriorityQ for Consumers"""
    1552          yield get,self,buffer,4,priority
    1553          doneList.append(self.name)
    1554
    1555  ### Begin classes for testConPrinciple (Level) ###
    1556 -class  ProducerPrincL(Process):
    1557 -    def __init__(self,sim=None):
    1558          Process.__init__(self,sim=sim)
    1559 -    def produce(self,buffer,productionTime):
    1560          while True:
    1561              assert not(buffer.amount>0 and len(buffer.getQ)>0),\
    1562                  "Consumer(s) waiting while buffer not empty"
    1563              yield hold,self,productionTime
    1564              yield put,self,buffer,1
    1565
    1566 -class ConsumerPrincL(Process):
    1567 -    def __init__(self,sim=None):
    1568          Process.__init__(self,sim=sim)
    1569 -    def consume(self,buffer,consumptionTime):
    1570          while True:
    1571              assert not(buffer.amount==0 and len(buffer.putQ)>0),\
    1572                  "Producer(s) waiting while buffer empty"
    1573              yield get,self,buffer,1
    1574              yield hold,self,consumptionTime
    1575
    1576  ### End classes for testConPrinciple (Level) ###
    1577
    1578 -class makeLevelTestcase(unittest.TestCase):
    1579 -    def testStatic(self):
    1580          """Tests initialization of Level instances
    1581          """
    1582          s=Simulation()
    1583          s.initialize()
    1584          a=Level(sim=s)
    1585          assert a.capacity==sys.maxint,"wrong capacity:%s"%a
    1586          assert a.amount==0,"wrong buffer content: %s"%a
    1587          assert a.name=="a_level","wrong name: %s"%a
    1588          assert not a.monitored,"should not be monitored: %s"%a
    1589          assert a.putQMon is None,"should not have putQMon: %s"%a
    1590          assert a.getQMon is None,"should not have getQMon: %s"%a
    1591          assert a.bufferMon is None,"should not have bufferMon: %s"%a
    1592          assert a.putQType.__name__=="FIFO" and a.getQType.__name__=="FIFO",\
    1593                 "putQType and getQType should be FIFO: %s"%a
    1594
    1595          b=Level(name="b",initialBuffered=10.0,monitored=True,capacity=12,
    1596                      putQType=PriorityQ,sim=s)
    1597          a=Level(sim=s)
    1598          assert b.capacity==12,"wrong capacity:%s"%b
    1599          assert b.amount==10,"wrong buffer content: %s"%b
    1600          assert b.name=="b","wrong name: %s"%b
    1601          assert b.monitored,"should be monitored: %s"%b
    1602          assert not (b.putQMon is None),"should have putQMon: %s"%b
    1603          assert not (b.getQMon is None),"should have getQMon: %s"%b
    1604          assert not (b.bufferMon is None),"should have bufferMon: %s"%b
    1605          assert b.putQType.__name__=="PriorityQ",\
    1606                 "putQType should be PriorityQ: %s"%b
    1607          assert b.getQType.__name__=="FIFO",\
    1608                  "getQType should be PriorityQ: %s"%b
    1609
    1610 -    def testConProdPrinciple(self):
    1611          """Level: tests basic Producer/Consumer principles:
    1612          -   Consumers must not be waiting while Level buffer value > 0,
    1613          -   Producers must not be waiting while Level buffer value == 0
    1614          """
    1615          s=Simulation()
    1616          s.initialize()
    1617          bufferSize=1
    1618          productionTime=1
    1619          consumptionTime=5
    1620          endtime=50
    1621          buffer=Level(capacity=bufferSize,sim=s)
    1622          consumer=ConsumerPrincL(sim=s)
    1623          s.activate(consumer,consumer.consume(buffer,consumptionTime))
    1624          producer=ProducerPrincL(sim=s)
    1625          s.activate(producer,producer.produce(buffer,productionTime))
    1626          s.simulate(until=endtime)
    1627
    1628 -    def testConProd1(self):
    1629          """Level: tests put/get in 1 Producer/ 1 Consumer scenario"""
    1630          s=Simulation()
    1631          s.initialize()
    1632          buffer=Level(initialBuffered=0,sim=s)
    1633          p=Producer(sim=s)
    1634          s.activate(p,p.produce(buffer))
    1635          c=Consumer(sim=s)
    1636          s.activate(c,c.consume(buffer))
    1637          s.simulate(until=100)
    1638          assert Producer.produced-Consumer.consumed==buffer.amount,\
    1639              "items produced/consumed/buffered do not tally: %s %s %s"\
    1640                  %(Producer.produced,Consumer.consumed,buffer.amount)
    1641
    1642 -    def testConProdM(self):
    1643          """Level: tests put/get in multiple Producer/Consumer scenario"""
    1644          s=Simulation()
    1645          s.initialize()
    1646          buffer=Level(initialBuffered=0,sim=s)
    1647          Producer.produced=0
    1648          Consumer.consumed=0
    1649          for i in range(2):
    1650              c=Consumer(sim=s)
    1651              s.activate(c,c.consume(buffer))
    1652          for i in range(3):
    1653              p=Producer(sim=s)
    1654              s.activate(p,p.produce(buffer))
    1655          s.simulate(until=10)
    1656          assert Producer.produced-Consumer.consumed==buffer.amount,\
    1657              "items produced/consumed/buffered do not tally: %s %s %s"\
    1658                  %(Producer.produced,Consumer.consumed,buffer.amount)
    1659
    1660 -    def testConProdPriorM(self):
    1661          """Level: tests put/get in multiple Producer/Consumer scenario,
    1662          with Producers having different priorities.
    1663          How: Producers forced to queue; all after first should be done in
    1664          priority order
    1665          """
    1666          global doneList
    1667          doneList=[]
    1668          s=Simulation()
    1669          s.initialize()
    1670          buffer=Level(capacity=7,putQType=PriorityQ,monitored=True,sim=s)
    1671          for i in range(4):
    1672              p=Producer(i,sim=s)
    1673              pPriority=i
    1674              s.activate(p,p.producePriority(buffer=buffer,priority=pPriority))
    1675          c=Consumer(sim=s)
    1676          s.activate(c,c.consume1(buffer=buffer))
    1677          s.simulate(until=100)
    1678          assert doneList==[0,3,2,1],"puts were not done in priority order: %s"\
    1679                                      %doneList
    1680
    1681 -    def testConPriorProdM(self):
    1682          """Level: tests put/get in multiple Producer/Consumer scenario, with
    1683          Consumers having different priorities.
    1684          How: Consumers forced to queue; all after first should be done in
    1685          priority order
    1686          """
    1687          global doneList
    1688          doneList=[]
    1689          s=Simulation()
    1690          s.initialize()
    1691          buffer=Level(capacity=7,getQType=PriorityQ,monitored=True,sim=s)
    1692          for i in range(4):
    1693              c=Consumer(i,sim=s)
    1694              cPriority=i
    1695              s.activate(c,c.consumePriority(buffer=buffer,priority=cPriority))
    1696          p=Producer(sim=s)
    1697          s.activate(p,p.produce1(buffer=buffer))
    1698          s.simulate(until=100)
    1699          assert doneList==[3,2,1,0],"gets were not done in priority order: %s"\
    1700                                      %doneList
    1701
    1702 -def makeLevelSuite():
    1703      suite = unittest.TestSuite()
    1704      testStatic = makeLevelTestcase("testStatic")
    1705      testConProdPrinciple=makeLevelTestcase("testConProdPrinciple")
    1706      testConProd1=makeLevelTestcase("testConProd1")
    1707      testConProdM=makeLevelTestcase("testConProdM")
    1708      testConProdPriorM=makeLevelTestcase("testConProdPriorM")
    1709      testConPriorProdM=makeLevelTestcase("testConPriorProdM")
    1710      suite.addTests([testStatic,testConProdPrinciple,testConProd1,
    1711                      testConProdM,testConProdPriorM,testConPriorProdM])
    1712      return suite
    1713
    1714  ## ------------------------------------------------------------------
    1715  ##             TEST "yield get,self,store,whatToGet" and
    1716  ##                  "yield put,self,store,whatToPut"
    1717  ##             for Store instances
    1718  ## ------------------------------------------------------------------
    1719
    1720 -class ProducerWidget(Process):
    1721      produced=0
    1722 -    def __init__(self,name="",sim=None):
    1723          Process.__init__(self,name=name,sim=sim)
    1724 -    def produce(self,buffer):
    1725          for i in range(4):
    1726              ProducerWidget.produced+=1
    1727              yield put,self,buffer,[Widget(weight=5)]
    1728              yield hold,self,1
    1729 -    def producePriority(self,buffer,priority):
    1730          """PriorityQ for Producers"""
    1731          ProducerWidget.produced+=4
    1732          toStore=[Widget(weight=5)]*4
    1733          yield put,self,buffer,toStore,priority
    1734          yield hold,self,1
    1735          self.done=self.sim.now()
    1736          doneList.append(self.name)
    1737 -    def produce1(self,buffer):
    1738          for i in range(4):
    1739              yield put,self,buffer,[Widget(weight=5)]*4
    1740              yield hold,self,1
    1741 -    def produceUnordered(self,buffer):
    1742          produced=[Widget(weight=i) for i in [9,1,8,2,7,3,6,4,5]]
    1743          yield put,self,buffer,produced
    1744
    1745 -class ConsumerWidget(Process):
    1746      consumed=0
    1747 -    def __init__(self,name="",sim=None):
    1748          Process.__init__(self,name=name,sim=sim)
    1749 -    def consume(self,buffer):
    1750          """FIFO"""
    1751          yield get,self,buffer
    1752          ConsumerWidget.consumed+=1
    1753          assert len(self.got)==1,"wrong self.got: %s"%self.got
    1754          yield get,self,buffer,3
    1755          ConsumerWidget.consumed+=3
    1756          assert len(self.got)==3,"wrong self.got: %s"%self.got
    1757
    1758 -    def consume1(self,buffer):
    1759          """producer PriorityQ, consumer FIFO"""
    1760          while True:
    1761              yield get,self,buffer,2
    1762              yield hold,self,1
    1763
    1764 -    def consumePriority(self,buffer,priority):
    1765          """PriorityQ for Consumers"""
    1766          yield get,self,buffer,4,priority
    1767          doneList.append(self.name)
    1768
    1769 -    def consumeSorted(self,buffer,gotten):
    1770          yield get,self,buffer
    1771          gotten.append(self.got[0].weight)
    1772
    1773 -class Widget:
    1774 -    def __init__(self,weight):
    1775          self.weight=weight
    1776
    1777 -def mySortFunc(self,par):
    1778      """Sorts Widget instances by weight attribute."""
    1779      tmplist=[(x.weight,x) for x in par]
    1780      tmplist.sort()
    1781      return [x for (key,x) in tmplist]
    1782
    1783  ### Begin classes for testConPrinciple (Store) ###
    1784 -class  ProducerPrincS(Process):
    1785 -    def __init__(self,sim=None):
    1786          Process.__init__(self,sim=sim)
    1787 -    def produce(self,buffer,productionTime):
    1788          while True:
    1789              assert not(buffer.nrBuffered>0 and len(buffer.getQ)>0),\
    1790                  "Consumer(s) waiting while buffer not empty"
    1791              yield hold,self,productionTime
    1792              product=WidgetPrinc()
    1793              yield put,self,buffer,[product]
    1794
    1795 -class ConsumerPrincS(Process):
    1796 -    def __init__(self,sim=None):
    1797          Process.__init__(self,sim=sim)
    1798 -    def consume(self,buffer,consumptionTime):
    1799          while True:
    1800              assert not(buffer.nrBuffered==0 and buffer.putQ),\
    1801                  "Producer(s) waiting while buffer empty"
    1802              yield get,self,buffer,1
    1803              yield hold,self,consumptionTime
    1804
    1805 -class WidgetPrinc:
    1806      pass
    1807
    1808 -class FilterConsumer(Process):
    1809      """Used in testBufferFilter"""
    1810 -    def __init__(self,sim=None):
    1811          Process.__init__(self,sim=sim)
    1812 -    class Widget:
    1813 -        def __init__(self,weighs):
    1814              self.weight=weighs
    1815
    1816 -    def getItems(self,store,a,b):
    1817          """get all items with weight between a and b"""
    1818          def between_a_and_b(buf):
    1819              res=[]
    1820              for item in buf:
    1821                  if a<item.weight<b:
    1822                      res.append(item)
    1823
    1824          all=store.buffered
    1825          yield get,self,store,between_a_and_b
    1826          "All retrieved items weight in range?"
    1827          for it in self.got:
    1828              assert a<it.weight<b,"weight %s not in range %s..%s"\
    1829                                   %(it.weight,a,b)
    1830          "Any item fitting filter pred left in buffer?"
    1831          for it in store.buffer:
    1832              assert not (a<it.weight<b),\
    1833                  "item left in buffer which fits filter (%s<%s<%s)"\
    1834                  %(a,it.weight,b)
    1835          "All items either in store.buffer of self.got?"
    1836          for it in all:
    1837              assert (it in self.buffer) or (it in self.got),\
    1838                     "item w. weight %s neither in store nor in got"%it.weight
    1839
    1840  ### End classes for testConPrinciple (Store) ###
    1841
    1842 -class makeStoreTestcase(unittest.TestCase):
    1843 -    def testStatic(self):
    1844          """Store: tests initialization of Store instances
    1845          """
    1846          s=Simulation()
    1847          s.initialize()
    1848          a=Store(sim=s)
    1849          assert a.capacity==sys.maxint,"wrong capacity:%s"%a
    1850          assert a.nrBuffered==0,"wrong buffer content: %s"%a
    1851          assert a.name=="a_store","wrong name: %s"%a
    1852          assert not a.monitored,"should not be monitored: %s"%a
    1853          assert a.putQMon is None,"should not have putQMon: %s"%a
    1854          assert a.getQMon is None,"should not have getQMon: %s"%a
    1855          assert a.bufferMon is None,"should not have bufferMon: %s"%a
    1856          assert a.putQType.__name__=="FIFO" and a.getQType.__name__=="FIFO",\
    1857                 "putQType and getQType should be FIFO: %s"%a
    1858
    1859          stored=[Widget(weight=5)]*10
    1860          b=Store(name="b",initialBuffered=stored,monitored=True,capacity=12,
    1861                      putQType=PriorityQ,sim=s)
    1862          assert b.capacity==12,"wrong capacity:%s"%b
    1863          assert b.nrBuffered==10,"wrong buffer content: %s"%b
    1864          assert b.name=="b","wrong name: %s"%b
    1865          assert b.monitored,"should be monitored: %s"%b
    1866          assert not (b.putQMon is None),"should have putQMon: %s"%b
    1867          assert not (b.getQMon is None),"should have getQMon: %s"%b
    1868          assert not (b.bufferMon is None),"should have bufferMon: %s"%b
    1869          assert b.putQType.__name__=="PriorityQ",\
    1870                 "putQType should be PriorityQ: %s"%b
    1871          assert b.getQType.__name__=="FIFO",\
    1872                  "getQType should be PriorityQ: %s"%b
    1873
    1874 -    def testConProdPrinciple(self):
    1875          """Store: tests basic Producer/Consumer principles:
    1876          -   Consumers must not be waiting while items in Store buffer,
    1877          -   Producers must not be waiting while space available in Store buffer
    1878          """
    1879          bufferSize=1
    1880          productionTime=1
    1881          consumptionTime=5
    1882          endtime=50
    1883          s=Simulation()
    1884          s.initialize()
    1885          buffer=Store(capacity=bufferSize,sim=s)
    1886          consumer=ConsumerPrincS(sim=s)
    1887          s.activate(consumer,consumer.consume(buffer,consumptionTime))
    1888          producer=ProducerPrincS(sim=s)
    1889          s.activate(producer,producer.produce(buffer,productionTime))
    1890          s.simulate(until=endtime)
    1891
    1892 -    def testConProd1(self):
    1893          """Store: tests put/get in 1 Producer/ 1 Consumer scenario"""
    1894          s=Simulation()
    1895          s.initialize()
    1896          buffer=Store(initialBuffered=[],sim=s)
    1897          p=ProducerWidget(sim=s)
    1898          s.activate(p,p.produce(buffer))
    1899          c=ConsumerWidget(sim=s)
    1900          s.activate(c,c.consume(buffer))
    1901          s.simulate(until=100)
    1902          assert \
    1903             ProducerWidget.produced-ConsumerWidget.consumed==buffer.nrBuffered,\
    1904             "items produced/consumed/buffered do not tally: %s %s %s"\
    1905             %(ProducerWidget.produced,ConsumerWidget.consumed,buffer.nrBuffered)
    1906
    1907 -    def testConProdM(self):
    1908          """Store: tests put/get in multiple Producer/Consumer scenario"""
    1909          s=Simulation()
    1910          s.initialize()
    1911          buffer=Store(initialBuffered=[],sim=s)
    1912          ProducerWidget.produced=0
    1913          ConsumerWidget.consumed=0
    1914          for i in range(2):
    1915              c=ConsumerWidget(sim=s)
    1916              s.activate(c,c.consume(buffer))
    1917          for i in range(3):
    1918              p=ProducerWidget(sim=s)
    1919              s.activate(p,p.produce(buffer))
    1920          s.simulate(until=10)
    1921          assert ProducerWidget.produced-ConsumerWidget.consumed==buffer.nrBuffered,\
    1922              "items produced/consumed/buffered do not tally: %s %s %s"\
    1923              %(ProducerWidget.produced,ConsumerWidget.consumed,buffer.nrBuffered)
    1924
    1925 -    def testConProdPriorM(self):
    1926          """Store: Tests put/get in multiple Producer/Consumer scenario,
    1927          with Producers having different priorities.
    1928          How; Producers forced to queue; all after first should be done in
    1929          priority order
    1930          """
    1931          global doneList
    1932          doneList=[]
    1933          s=Simulation()
    1934          s.initialize()
    1935          buffer=Store(capacity=7,putQType=PriorityQ,monitored=True,sim=s)
    1936          for i in range(4):
    1937              p=ProducerWidget(name=i,sim=s)
    1938              pPriority=i
    1939              s.activate(p,p.producePriority(buffer=buffer,priority=pPriority))
    1940          c=ConsumerWidget(sim=s)
    1941          s.activate(c,c.consume1(buffer=buffer))
    1942          s.simulate(until=100)
    1943          assert doneList==[0,3,2,1],"puts were not done in priority order: %s"\
    1944                                      %doneList
    1945
    1946 -    def testConPriorProdM(self):
    1947          """Tests put/get in multiple Producer/Consumer scenario, with
    1948          Consumers having different priorities.
    1949          How; Consumers forced to queue; all after first should be done in
    1950          priority order
    1951          """
    1952          global doneList
    1953          doneList=[]
    1954          s=Simulation()
    1955          s.initialize()
    1956          buffer=Store(capacity=7,getQType=PriorityQ,monitored=True,sim=s)
    1957          for i in range(4):
    1958              c=ConsumerWidget(name=str(i),sim=s)
    1959              cPriority=i
    1960              s.activate(c,c.consumePriority(buffer=buffer,priority=cPriority))
    1961          p=ProducerWidget(sim=s)
    1962          s.activate(p,p.produce1(buffer=buffer))
    1963          s.simulate(until=100)
    1964          assert doneList==["3","2","1","0"],\
    1965                "gets were not done in priority order: %s"%doneList
    1966
    1967 -    def testBufferSort(self):
    1968          """Tests the optional sorting of theBuffer by applying a user-defined
    1969          sort function."""
    1970          s=Simulation()
    1971          s.initialize()
    1972          gotten=[]
    1973          sortedStore=Store(sim=s)
    1974          sortedStore.addSort(mySortFunc)
    1975          p=ProducerWidget(sim=s)
    1976          s.activate(p,p.produceUnordered(sortedStore))
    1977          for i in range(9):
    1978              c=ConsumerWidget(sim=s)
    1979              s.activate(c,c.consumeSorted(buffer=sortedStore,gotten=gotten),at=1)
    1980          s.simulate(until=10)
    1981          assert gotten==[1,2,3,4,5,6,7,8,9],"sort wrong: %s"%gotten
    1982
    1983 -    def testBufferFilter(self):
    1984          """Tests get from a Store with a filter function
    1985          """
    1986          s=Simulation()
    1987          s.initialize()
    1988          ItClass=FilterConsumer.Widget
    1989          all=[ItClass(1),ItClass(4),ItClass(6),ItClass(12)]
    1990          st=Store(initialBuffered=all)
    1991          fc=FilterConsumer()
    1992          minw=2;maxw=10
    1993          s.activate(fc,fc.getItems(store=st,a=minw,b=maxw))
    1994          s.simulate(until=1)
    1995
    1996 -def makeStoreSuite():
    1997      suite = unittest.TestSuite()
    1998      testStatic = makeStoreTestcase("testStatic")
    1999      testConProdPrinciple=makeStoreTestcase("testConProdPrinciple")
    2000      testConProd1=makeStoreTestcase("testConProd1")
    2001      testConProdM=makeStoreTestcase("testConProdM")
    2002      testConProdPriorM=makeStoreTestcase("testConProdPriorM")
    2003      testConPriorProdM=makeStoreTestcase("testConPriorProdM")
    2004      testBufferSort=makeStoreTestcase("testBufferSort")
    2005      testBufferFilter=makeStoreTestcase("testBufferFilter")
    2006      suite.addTests([testStatic,testConProdPrinciple,testConProd1,
    2007                      testConProdM,testConProdPriorM,testConPriorProdM,
    2008                      testBufferSort,testBufferFilter])
    2009      return suite
    2010
    2011  ## ------------------------------------------------------------------
    2012  ##
    2013  ##  Store: Tests for compound get/put
    2014  ##
    2015  ## ------------------------------------------------------------------
    2016 -class TBT(Process):
    2017      """Store: For testBasicTime"""
    2018 -    def __init__(self,sim=None):
    2019          Process.__init__(self,sim=sim)
    2020 -    def tbt(self,store):
    2021          yield get,self,store,1
    2022          assert self.got,"Did not get Item"
    2023          yield (get,self,store,1),(hold,self,5)
    2024          if self.acquired(store):
    2025              assert len(self.got)==1,"did not get 1 Item"
    2026          else:
    2027              assert not self.got and self.sim.now()==5 and not store.getQ,\
    2028                     "time renege not working"
    2029
    2030 -class TBE(Process):
    2031      """Store: For testBasicEvent"""
    2032 -    def __init__(self,name="",sim=None):
    2033          Process.__init__(self,sim=sim)
    2034 -    def tbe(self,store,trigger):
    2035          yield get,self,store,1
    2036          assert self.got,"Did not get Item"
    2037          yield (get,self,store,1),(waitevent,self,trigger)
    2038          if self.acquired(store):
    2039              assert False, "should have reneged"
    2040          else:
    2041              assert self.eventsFired[0]==trigger and self.sim.now()==5 \
    2042                  and not store.getQ,"event renege not working"
    2043
    2044 -class TBEtrigger(Process):
    2045      """Store: For testBasicEvent"""
    2046 -    def __init__(self,sim=None):
    2047          Process.__init__(self,sim=sim)
    2048 -    def fire(self,trigger):
    2049          yield hold,self,5
    2050          trigger.signal()
    2051
    2052
    2053 -class TBTput(Process):
    2054      """Store: for testBasicTimePut"""
    2055 -    def __init__(self,sim=None):
    2056          Process.__init__(self,sim=sim)
    2057 -    def tbt(self,store):
    2058          class Item:pass
    2059          yield (put,self,store,[Item()]),(hold,self,4)
    2060          if self.stored(store):
    2061              assert store.nrBuffered==1 and not store.putQ,\
    2062                     "put did not execute"
    2063          else:
    2064              assert False,"should not have reneged"
    2065          yield (put,self,store,[Item()]),(hold,self,5)
    2066          if self.stored(store):
    2067              assert False,"should have reneged"
    2068          else:
    2069              assert store.nrBuffered==1 and not store.putQ,\
    2070                     "renege not working correctly"
    2071
    2072 -class TBEput(Process):
    2073      """Store: for testBasicEventPut"""
    2074 -    def __init__(self,sim=None):
    2075          Process.__init__(self,sim=sim)
    2076 -    def tbe(self,store,trigger):
    2077          class Item:pass
    2078          yield (put,self,store,[Item()]),(waitevent,self,trigger)
    2079          if self.stored(store):
    2080              assert store.nrBuffered==1 and not store.putQ,\
    2081                     "put did not execute"
    2082          else:
    2083              assert False,"should have not have reneged"
    2084          yield (put,self,store,[Item()]),(waitevent,self,trigger)
    2085          if self.stored(store):
    2086              assert False,"should have reneged"
    2087          else:
    2088              assert self.sim.now()==5 and self.eventsFired[0]==trigger\
    2089                     and not store.putQ,"renege not working correctly"
    2090
    2091 -class TBEtriggerPut(Process):
    2092      """Store: For testBasicEventPut"""
    2093 -    def __init__(self,sim=None):
    2094          Process.__init__(self,sim=sim)
    2095 -    def fire(self,trigger):
    2096          yield hold,self,5
    2097          trigger.signal()
    2098
    2099 -class makeStoreCompTestcase(unittest.TestCase):
    2100      """Store: Testcase for compound get statements"""
    2101      ## ------------------------------------------------------------------
    2102      ##             TEST "yield (get,self,store),(hold,self,time)"
    2103      ##                   == timeout renege
    2104      ##             for both unmonitored and monitored Stores
    2105      ## ------------------------------------------------------------------
    2106
    2107 -    def testBasicTime(self):
    2108          """Store (unmonitored):
    2109          test 'yield (get,self,store),(hold,self,timeout)"""
    2110          s=Simulation()
    2111          s.initialize()
    2112          class Item:pass
    2113          st=Store(initialBuffered=[Item()],sim=s)
    2114          t=TBT(sim=s)
    2115          s.activate(t,t.tbt(store=st))
    2116          s.simulate(until=10)
    2117
    2118      ## ------------------------------------------------------------------
    2119      ##             TEST "yield (put,self,store),(hold,self,time)"
    2120      ##                   == timeout renege
    2121      ##             for both unmonitored and monitored Stores
    2122      ## ------------------------------------------------------------------
    2123 -    def testBasicTimePut(self):
    2124          """Store (unmonitored):
    2125          test 'yield (put,self,store),(hold,self,time)"""
    2126          s=Simulation()
    2127          s.initialize()
    2128          st=Store(capacity=1,sim=s)
    2129          t=TBTput(sim=s)
    2130          s.activate(t,t.tbt(store=st))
    2131          s.simulate(until=10)
    2132
    2133 -    def testBasicTimePutM(self):
    2134          """Store (monitored):
    2135          test monitors with 'yield (put,self,store),(hold,self,time)"""
    2136          s=Simulation()
    2137          s.initialize()
    2138          st=Store(capacity=1,monitored=True,sim=s)
    2139          t=TBTput(sim=s)
    2140          s.activate(t,t.tbt(store=st))
    2141          s.simulate(until=10)
    2142          #First put succeeds, second attempt reneges at t=5?
    2143          assert st.putQMon==[[0,0],[0,1],[5,0]],"putQMon wrong: %s"\
    2144                                                 %st.putQMon
    2145          #First Item goes into buffer at t=0, second not (renege)?
    2146          assert st.bufferMon==[[0,0],[0,1]],"bufferMon wrong: %s"%st.bufferMon
    2147
    2148      ## ------------------------------------------------------------------
    2149      ##             TEST "yield (get,self,store),(waitevent,self,event)"
    2150      ##                   == event renege
    2151      ##             for both unmonitored and monitored Stores
    2152      ## ------------------------------------------------------------------
    2153 -    def testBasicEvent(self):
    2154          """Store (unmonitored):
    2155          test 'yield (get,self,store),(waitevent,self,event)"""
    2156          si=Simulation()
    2157          si.initialize()
    2158          class Item:pass
    2159          st=Store(initialBuffered=[Item()],sim=si)
    2160          trig=SimEvent(sim=si)
    2161          t=TBE(sim=si)
    2162          si.activate(t,t.tbe(store=st,trigger=trig))
    2163          tr=TBEtrigger(sim=si)
    2164          si.activate(tr,tr.fire(trigger=trig))
    2165          si.simulate(until=10)
    2166
    2167      ## ------------------------------------------------------------------
    2168      ##             TEST "yield (put,self,store),(waitevent,self,event)"
    2169      ##                   == event renege
    2170      ##             for both unmonitored and monitored Stores
    2171      ## ------------------------------------------------------------------
    2172 -    def testBasicEventPut(self):
    2173          """Store (unmonitored):
    2174          test 'yield (put,self,store),(waitevent,self,event)"""
    2175          si=Simulation()
    2176          si.initialize()
    2177          s=SimEvent(sim=si)
    2178          store=Store(capacity=1,sim=si)
    2179          t=TBEtriggerPut(sim=si)
    2180          si.activate(t,t.fire(trigger=s))
    2181          tb=TBEput(sim=si)
    2182          si.activate(tb,tb.tbe(store=store,trigger=s))
    2183          si.simulate(until=10)
    2184
    2185 -    def testBasicEventPutM(self):
    2186          """Store (monitored):
    2187          test monitors with 'yield (put,self,store),(waitevent,self,event)"""
    2188          si=Simulation()
    2189          si.initialize()
    2190          s=SimEvent(sim=si)
    2191          st=Store(capacity=1,monitored=True,sim=si)
    2192          t=TBEtriggerPut(sim=si)
    2193          si.activate(t,t.fire(trigger=s))
    2194          tb=TBEput(sim=si)
    2195          si.activate(tb,tb.tbe(store=st,trigger=s))
    2196          si.simulate(until=10)
    2197          #First put succeeds, second attempt reneges at t=5?
    2198          assert st.putQMon==[[0,0],[0,1],[5,0]],"putQMon wrong: %s"\
    2199                                                 %st.putQMon
    2200          #First Item goes into buffer at t=0, second not (renege)?
    2201          assert st.bufferMon==[[0,0],[0,1]],"bufferMon wrong: %s"%st.bufferMon
    2202
    2203 -def makeStoreCompSuite():
    2204      suite = unittest.TestSuite()
    2205      ## Unmonitored Stores
    2206      testBasicTime  = makeStoreCompTestcase("testBasicTime")
    2207      testBasicEvent = makeStoreCompTestcase("testBasicEvent")
    2208      testBasicTimePut  = makeStoreCompTestcase("testBasicTimePut")
    2209      testBasicEventPut = makeStoreCompTestcase("testBasicEventPut")
    2210  ##    ## Monitored Stores
    2211      testBasicTimePutM = makeStoreCompTestcase("testBasicTimePutM")
    2212      testBasicEventPutM = makeStoreCompTestcase("testBasicEventPutM")
    2213
    2214      suite.addTests([testBasicTime,testBasicTimePut,testBasicTimePutM,
    2215                      testBasicEvent,testBasicEventPut,testBasicEventPutM
    2216                     ])
    2217      return suite
    2218
    2219  ## ------------------------------------------------------------------
    2220  ##
    2221  ##  Level: Tests for compound get
    2222  ##
    2223  ## ------------------------------------------------------------------
    2224 -class TBTLev(Process):
    2225      """Level: For testBasicTime"""
    2226 -    def __init__(self,**par):
    2227          Process.__init__(self,**par)
    2228 -    def tbt(self,level):
    2229          yield get,self,level,1
    2230          assert self.got,"did not get 1 unit"
    2231          yield (get,self,level,1),(hold,self,5)
    2232          if self.acquired(level):
    2233              assert self.got==1,"did not get 1 unit"
    2234          else:
    2235              assert not self.got and self.sim.now()==5,\
    2236                     "time renege not working"
    2237
    2238 -class TBELev(Process):
    2239      """Level: For testBasicEvent"""
    2240 -    def __init__(self,**par):
    2241          Process.__init__(self,**par)
    2242 -    def tbe(self,level,trigger):
    2243          yield get,self,level,1
    2244          assert self.got,"did not get 1 unit"
    2245          yield (get,self,level,1),(waitevent,self,trigger)
    2246          if self.acquired(level):
    2247              assert self.got==1,"did not get 1 Item"
    2248          else:
    2249              assert self.sim.now()==5.5 and self.eventsFired[0]==trigger,\
    2250                     "event renege not working"
    2251
    2252 -class TBEtriggerLev(Process):
    2253      """Level: For testBasicEvent"""
    2254 -    def __init__(self,**par):
    2255          Process.__init__(self,**par)
    2256 -    def fire(self,trigger):
    2257          yield hold,self,5.5
    2258          trigger.signal()
    2259
    2260 -class TBTLevPut(Process):
    2261      """Level: For testBasicTimePut"""
    2262 -    def __init__(self,**par):
    2263          Process.__init__(self,**par)
    2264 -    def tbt(self,level):
    2265          yield put,self,level,1
    2266          assert level.amount,"did not put 1 unit"
    2267          yield (put,self,level,1),(hold,self,5)
    2268          if self.stored(level):
    2269              assert False,"should have reneged"
    2270          else:
    2271              assert level.amount==1 and self.sim.now()==5,\
    2272                     "time renege not working"
    2273
    2274 -class TBELevPut(Process):
    2275      """Level: For testBasicEventPut and testBasicEventPutM"""
    2276 -    def __init__(self,**par):
    2277          Process.__init__(self,**par)
    2278 -    def tbe(self,level,trigger):
    2279          yield (put,self,level,1),(waitevent,self,trigger)
    2280          if self.stored(level):
    2281              assert level.amount==1,"did not put 1 unit"
    2282          else:
    2283              assert False,"should not have reneged"
    2284          yield (put,self,level,1),(waitevent,self,trigger)
    2285          if self.stored(level):
    2286              assert False, "should have reneged"
    2287          else:
    2288              assert self.sim.now()==5.5 and self.eventsFired[0]==trigger ,\
    2289                     "renege not working"
    2290
    2291 -class TBEtriggerLevPut(Process):
    2292      """Level: For testBasicEventPut"""
    2293 -    def __init__(self,**par):
    2294          Process.__init__(self,**par)
    2295 -    def fire(self,trigger):
    2296          yield hold,self,5.5
    2297          trigger.signal()
    2298
    2299 -class makeLevelCompTestcase(unittest.TestCase):
    2300      """Level: Testcase for compound get and put statements"""
    2301      ## ------------------------------------------------------------------
    2302      ##             TEST "yield (get,self,level),(hold,self,time)"
    2303      ##                   == timeout renege
    2304      ##             for both unmonitored and monitored Levels
    2305      ## ------------------------------------------------------------------
    2306
    2307 -    def testBasicTime(self):
    2308          """Level (unmonitored):
    2309              test 'yield (get,self,level),(hold,self,timeout)
    2310          """
    2311          s=Simulation()
    2312          s.initialize()
    2313          l=Level(initialBuffered=1,sim=s)
    2314          t=TBTLev(sim=s)
    2315          s.activate(t,t.tbt(level=l))
    2316          s.simulate(until=10)
    2317
    2318      ## ------------------------------------------------------------------
    2319      ##             TEST "yield (put,self,store),(hold,self,time)"
    2320      ##                   == timeout renege
    2321      ##             for both unmonitored and monitored Stores
    2322      ## ------------------------------------------------------------------
    2323 -    def testBasicTimePut(self):
    2324          """Level (unmonitored):
    2325          test 'yield (put,self,level),(hold,self,timeout)"""
    2326          s=Simulation()
    2327          s.initialize()
    2328          l=Level(capacity=1,sim=s)
    2329          t=TBTLevPut(sim=s)
    2330          s.activate(t,t.tbt(level=l))
    2331          s.simulate(until=10)
    2332
    2333      ## ------------------------------------------------------------------
    2334      ##             TEST "yield (get,self,store),(waitevent,self,event)"
    2335      ##                   == event renege
    2336      ##             for both unmonitored and monitored Levels
    2337      ## ------------------------------------------------------------------
    2338 -    def testBasicEvent(self):
    2339          """Level (unmonitored):
    2340          test 'yield (get,self,level),(waitevent,self,event)"""
    2341          s=Simulation()
    2342          s.initialize()
    2343          l=Level(initialBuffered=1,sim=s)
    2344          trig=SimEvent(sim=s)
    2345          t=TBELev(sim=s)
    2346          s.activate(t,t.tbe(level=l,trigger=trig))
    2347          tr=TBEtriggerLev(sim=s)
    2348          s.activate(tr,tr.fire(trigger=trig))
    2349          s.simulate(until=10)
    2350
    2351 -    def testBasicEventM(self):
    2352          """Level (monitored):
    2353          test monitors with 'yield (get,self,level),(waitevent,self,event)"""
    2354          s=Simulation()
    2355          s.initialize()
    2356          l=Level(initialBuffered=1,monitored=True,sim=s)
    2357          trig=SimEvent(sim=s)
    2358          t=TBELev(sim=s)
    2359          s.activate(t,t.tbe(level=l,trigger=trig))
    2360          tr=TBEtriggerLev(sim=s)
    2361          s.activate(tr,tr.fire(trigger=trig))
    2362          s.simulate(until=10)
    2363          #First get (t=0) succeeded and second timed out at t=5.5?
    2364          assert l.getQMon==[[0,0],[0,1],[5.5,0]],"getQMon not working: %s"\
    2365                                                 %l.getQMon
    2366          #Level amount incr. then decr. by 1 (t=0), 2nd get reneged at t=5.5?
    2367          assert l.bufferMon==[[0,1],[0,0]],\
    2368                 "bufferMon not working: %s"%l.bufferMon
    2369
    2370      ## ------------------------------------------------------------------
    2371      ##             TEST "yield (put,self,store),(waitevent,self,event)"
    2372      ##                   == event renege
    2373      ##             for both unmonitored and monitored Levels
    2374      ## ------------------------------------------------------------------
    2375 -    def testBasicEventPut(self):
    2376          """Level (unmonitored):
    2377          test 'yield (put,self,level),(waitevent,self,event)"""
    2378          s=Simulation()
    2379          s.initialize()
    2380          l=Level(capacity=1,sim=s)
    2381          trig=SimEvent(sim=s)
    2382          t=TBELevPut(sim=s)
    2383          s.activate(t,t.tbe(level=l,trigger=trig))
    2384          tr=TBEtriggerLevPut(sim=s)
    2385          s.activate(tr,tr.fire(trigger=trig))
    2386          s.simulate(until=10)
    2387
    2388 -    def testBasicEventPutM(self):
    2389          """Level (monitored):
    2390          test monitors with 'yield (put,self,level),(waitevent,self,event)"""
    2391          s=Simulation()
    2392          s.initialize()
    2393          l=Level(capacity=1,monitored=True,sim=s)
    2394          trig=SimEvent(sim=s)
    2395          t=TBELevPut(sim=s)
    2396          s.activate(t,t.tbe(level=l,trigger=trig))
    2397          tr=TBEtriggerLevPut(sim=s)
    2398          s.activate(tr,tr.fire(trigger=trig))
    2399          s.simulate(until=10)
    2400          "First put succeeds, second reneges at t=5.5?"
    2401          assert l.putQMon==[[0,0],[0,1],[5.5,0]],"putQMon wrong: %s"\
    2402                                                  %l.putQMon
    2403          "1 unit added at t=0, renege at t=5 before 2nd unit added?"
    2404          assert l.bufferMon==[[0,0],[0,1]],"bufferMon wrong: %s"%l.bufferMon
    2405
    2406 -def makeLevelCompSuite():
    2407      suite = unittest.TestSuite()
    2408      ## Unmonitored Levels
    2409      testBasicTime  = makeLevelCompTestcase("testBasicTime")
    2410      testBasicEvent = makeLevelCompTestcase("testBasicEvent")
    2411      testBasicTimePut = makeLevelCompTestcase("testBasicTimePut")
    2412      testBasicEventPut = makeLevelCompTestcase("testBasicEventPut")
    2413  ##    ## Monitored Levels
    2414      testBasicEventM = makeLevelCompTestcase("testBasicEventM")
    2415      testBasicEventPutM = makeLevelCompTestcase("testBasicEventPutM")
    2416
    2417      suite.addTests([testBasicTime,testBasicEvent,testBasicTimePut,
    2418                      testBasicEventM,testBasicEventPut,testBasicEventPutM])
    2419      return suite
    2420
    2421  if __name__ == '__main__':
    2422      alltests = unittest.TestSuite((
    2423                                     makeSSuite(),
    2424                                     makeRSuite(),
    2425                                     makeISuite(),
    2426                                     makePSuite(),
    2427                                     makeESuite(),
    2428                                     makeWSuite(),
    2429                                     makeTOSuite(),
    2430                                     makeEvtRenegeSuite(),
    2431                                     makeLevelSuite(),
    2432                                     makeStoreSuite(),
    2433                                     makeStoreCompSuite(),
    2434                                     makeLevelCompSuite(),
    2435                                     makeMSuite()
    2436                                    ))
    2437
    2438      runner = unittest.TextTestRunner()
    2439      runner.run(alltests)
    2440  ##
    2441