Package SimPy :: Module testSimPy

[hide private]
[frames] | no frames]

# Source Code for Module SimPy.testSimPy

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