Package SimPy :: Module testSimPyTraceOO

[hide private]
[frames] | no frames]

# Source Code for Module SimPy.testSimPyTraceOO

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