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