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

Source Code for Module SimPy.testSimPyTrace

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