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

Source Code for Module SimPy.testSimPyStep

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