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

Source Code for Module SimPy.testSimPyStep

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