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

# Source Code for Module SimPy.testSimPyTraceOO

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