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

Source Code for Module SimPy.testSimPyRT

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