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

Source Code for Module SimPy.testSimPy

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