Package SimPy :: Module testSimPyOO

[hide private]
[frames] | no frames]

# Source Code for Module SimPy.testSimPyOO

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