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

Source Code for Module SimPy.testSimPyTrace

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