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

Source Code for Module SimPy.testSimPyRT

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