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

Source Code for Module SimPy.testSimPyStep

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