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