Package SimPy :: Module testSimPyRT

[hide private]
[frames] | no frames]

# Source Code for Module SimPy.testSimPyRT

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