class TestDynamicNodesModel(unittest.TestCase): def setUp(self): self.simulation = Simulation() self.simulation.initialize() self.nodes = [] for _ in range(10): self.nodes.append( FakeNode( sim=self.simulation ) ) self.random = Mock() self.random.normalvariate.side_effect = lambda *args: args[0] - args[1]/2 # just to check how to configure different returns def get_nodes(self): return self.nodes @patch.object(NodeManager, 'getNodes') def test_configure(self, mock_method): mock_method.side_effect = self.get_nodes simulateUntil = 2000 model = DynamicNodesModel(simulateUntil, 500, 200) model._random = self.random model.configure() # test method self.simulation.simulate(until=simulateUntil) for node in self.get_nodes(): self.assertItemsEqual( ( (400, "down"), (800, "up"), (1200, "down"), (1600, "up") ), node.trace )
def __init__(self, configuration, callback=None): """ Args: - `callback`: A callback can be specified. This function will be \ called to report the advance of the simulation (useful for a \ progression bar). - `configuration`: The :class:`configuration \ <simso.configuration.Configuration>` of the simulation. Methods: """ Simulation.__init__(self) self._logger = Logger(self) self._measurements = [] task_info_list = configuration.task_info_list proc_info_list = configuration.proc_info_list self._cycles_per_ms = configuration.cycles_per_ms self.scheduler = configuration.scheduler_info.instantiate(self) try: self._etm = execution_time_models[configuration.etm]( self, len(proc_info_list)) except KeyError: print("Unknowned Execution Time Model.", configuration.etm) self._task_list = [] for task_info in task_info_list: self._task_list.append(Task(self, task_info)) # Init the processor class. This will in particular reinit the # identifiers to 0. Processor.init() # Initialization of the caches for cache in configuration.caches_list: cache.init() self._processors = [] for proc_info in proc_info_list: proc = Processor(self, proc_info) proc.caches = proc_info.caches self._processors.append(proc) # XXX: too specific. self.penalty_preemption = configuration.penalty_preemption self.penalty_migration = configuration.penalty_migration self._etm.init() self._duration = configuration.duration self.progress = Timer(self, Model._on_tick, (self, ), self.duration // 20 + 1, one_shot=False, in_ms=False) self._callback = callback self.scheduler.task_list = self._task_list self.scheduler.processors = self._processors self.results = None
def __init__(self, configuration, callback=None): """ Args: - `callback`: A callback can be specified. This function will be \ called to report the advance of the simulation (useful for a \ progression bar). - `configuration`: The :class:`configuration \ <simso.configuration.Configuration>` of the simulation. Methods: """ Simulation.__init__(self) self._logger = Logger(self) task_info_list = configuration.task_info_list proc_info_list = configuration.proc_info_list self._cycles_per_ms = configuration.cycles_per_ms self.scheduler = configuration.scheduler_info.instantiate(self) try: self._etm = execution_time_models[configuration.etm]( self, len(proc_info_list) ) except KeyError: print("Unknowned Execution Time Model.", configuration.etm) self._task_list = [] for task_info in task_info_list: self._task_list.append(Task(self, task_info)) # Init the processor class. This will in particular reinit the # identifiers to 0. Processor.init() # Initialization of the caches for cache in configuration.caches_list: cache.init() self._processors = [] for proc_info in proc_info_list: proc = Processor(self, proc_info) proc.caches = proc_info.caches self._processors.append(proc) # XXX: too specific. self.penalty_preemption = configuration.penalty_preemption self.penalty_migration = configuration.penalty_migration self._etm.init() self._duration = configuration.duration self.progress = Timer(self, Model._on_tick, (self,), self.duration // 20 + 1, one_shot=False, in_ms=False) self._callback = callback self.scheduler.task_list = self._task_list self.scheduler.processors = self._processors self.results = None
def setUp(self): self.simulation = Simulation() self.cache = Cache(self.simulation) for i in range(5): at = i * 10 record = PTRRecord("_http._tcp.local", "name%d._http._tcp.local"%i, ) self.cache.records.append(record) self.cache.pending_events.append((at, Cache.EVENT_KNOWN_ANSWER, record)) record = SVRRecord("name%d._http._tcp.local"%i, None, None) self.cache.records.append(record) self.cache.pending_events.append((at, Cache.EVENT_KNOWN_ANSWER, record)) record = TXTRecord("name%d._http._tcp.local"%i, {}) self.cache.records.append(record) self.cache.pending_events.append((at, Cache.EVENT_RENEW, record)) self.assertEquals(15, len(self.cache.records)) self.assertEquals(15, len(self.cache.pending_events)) self.sample_txt = TXTRecord("name0._http._tcp.local", {}) self.sample_svr = SVRRecord("name2._http._tcp.local", None, None) self.sample_ptr = PTRRecord("_http._tcp.local", "name4._http._tcp.local")
class TestOneNodeDownModel(unittest.TestCase): def setUp(self): self.simulation = Simulation() self.simulation.initialize() self.nodes = [] for _ in range(10): self.nodes.append( FakeNode( sim=self.simulation ) ) self.random = Mock() self.random.normalvariate.side_effect = lambda *args: args[0] - args[1]/2 # just to check how to configure different returns import random self.random.choice.side_effect = random.choice # otherwise choice method will be mocked! def get_nodes(self): return self.nodes @patch.object(NodeManager, 'getNodes') def test_configure(self, mock_method): mock_method.side_effect = self.get_nodes simulateUntil = 2000 model = OneNodeDownModel(simulateUntil, 500, 200) model._random = self.random model.configure() # test method self.simulation.simulate(until=simulateUntil) total_activity = [ (400, "down"), (800, "up"), (800, "down"), (1200, "up"), (1200, "down"), (1600, "up"), (1600, "down"), ] for node in self.get_nodes(): for trace in node.trace: self.assertTrue( trace in total_activity ) if trace[1] is "down" and trace[0]<1600: # if the node goes down, in 400 ms should go up again self.assertTrue( (trace[0]+400, "up") in node.trace ) total_activity.remove(trace) # all the traces should have been conveniently removed in the previous for self.assertEquals(0, len(total_activity))
class ActivatableTestCase(unittest.TestCase): # wrapper under test: activatable def setUp(self): self.simulation = Simulation() self.simulation.initialize() self.proc1 = SimpleProcess(sim=self.simulation) self.proc2 = SimpleProcess(sim=self.simulation) def test_exception_not_generator(self): self.proc1 = SimpleProcess(sim=self.simulation) try: self.proc1.not_generator(at=300) self.fail() except Exception, e: #print e pass
def setUp(self): self.simulation = Simulation() self.simulation.initialize() self.nodes = [] for _ in range(10): self.nodes.append( FakeNode( sim=self.simulation ) ) self.random = Mock() self.random.normalvariate.side_effect = lambda *args: args[0] - args[1]/2 # just to check how to configure different returns
def test_wait(self): s = Simulation() s.initialize() obj = ObjectWhichUsesTimer(timeToWait=10, sim=s) s.activate(obj, obj.do_whatever_you_do_in_simulation()) s.simulate(until=300) self.assertEquals(10, obj.time_after_waiting)
def setUp(self): self.simulation = Simulation() self.mdns_instance = Mock() self.mdns_instance.get_whitepage_record.return_value = None self.mdns_instance.notify_whitepage_changed.side_effect = self._log_event self.detector = NewWPDetector(self.mdns_instance, self.simulation) self.log = [] self.simulation.initialize()
def setUp(self): self.simulation = Simulation() self.browsing_subquery = SubQuery( name = "_services._dns-sd._udp.local", record_type = "PTR" ) self.sender = FakeSender(self.simulation) # used for the asserts self.querier = ContinuousQuerier(self.browsing_subquery, self.simulation, self.sender) self.querier._random = Mock() self.querier._random.random.side_effect = lambda *args: 0.5 self.simulation.initialize() self.simulation.activate(self.querier, self.querier.query_continuously())
class TestChaoticModel(unittest.TestCase): def setUp(self): self.simulation = Simulation() self.simulation.initialize() self.nodes = [] for _ in range(10): self.nodes.append( FakeNode( sim=self.simulation ) ) self.random = Mock() self.random.normalvariate.side_effect = lambda *args: args[0] - args[1]/2 # just to check how to configure different returns def _get_node_for_record(self, record): print record def patch_find_whitepage(self, model): model.find_whitepage = Mock() model.find_whitepage.return_value = self.nodes[0] # select the first as WP def test_run(self): model = ChaoticModel(self.simulation, 500, 200) model._random = self.random self.patch_find_whitepage(model) model.run(at=0) # test method self.simulation.simulate(until=2000) # WP from the previous loop goes up, current WP goes down # In this case the WP is always the same self.assertItemsEqual( ( (400, "down"), (800, "up"), (800, "down"), (1200, "up"), (1200, "down"), (1600, "up"), (1600, "down"), (2000, "up"), (2000, "down") ), self.nodes[0].trace ) for n in range( 1, len(self.nodes) ): self.assertEquals( 0, len(self.nodes[n].trace) )
class RequestInstanceTestCase(unittest.TestCase): def setUp(self): self.s = Simulation() self.s.initialize() def get_me(self): me = Mock() me.name = "origin" return me def get_unavailable_node(self, name): node = Mock() node.queueRequest.return_value = None node.name = name return node def get_available_node(self, name): n = FakeAvailableNode(name, self.s) n.processRequests(at=0) return n @patch('netuse.results.G._tracer', Mock()) # new global unrandomized variable def test_get_unanswered_nodes(self): nodes = [] nodes.append( self.get_available_node("aval1") ) nodes.append( self.get_unavailable_node("unaval") ) nodes.append( self.get_available_node("aval2") ) me = self.get_me() # otherwise weakref of RequestInstance will delete it ri = RequestInstance(me, nodes, "/fakeurl", sim=self.s) RequestManager.launchNormalRequest(ri) self.s.simulate(100000) unanswered = ri.get_unanswered_nodes() self.assertTrue( nodes[1].name in unanswered ) self.assertFalse( nodes[0].name in unanswered ) self.assertFalse( nodes[2].name in unanswered )
def initialize(self): """ Initializes the object. @rtype: NoneType """ self.__simInstance = Simulation() self.__simInstance.initialize() self.__simulationTime = 0 self.__currentSimulationTime = 0 self.__network = None self.__simulationProcessFactory = [] self.__resourcePeer = 0 self.__transactionNumber = 0 self.__transactionDateTimeStart = "" self.__transactionDateTimeStop = "" #self.__logger = SimulationLogger() #self.__logger.resgiterLoggingInfo("Create Simulation ") SimulationLogger().resgiterLoggingInfo("Create Simulation ")
def setUp(self): self.simulation = Simulation() self.simulation.initialize() self.obj1 = FakeClass(self.simulation) self.obj2 = FakeClass(self.simulation)
class AbstractSimulation(ISimulation): """ Defines the interface of simulation objects. @author: Luiz Gustavo @organization: Federal University of Rio de Janeiro """ def __init__(self): raise NotImplementedError() def initialize(self): """ Initializes the object. @rtype: NoneType """ self.__simInstance = Simulation() self.__simInstance.initialize() self.__simulationTime = 0 self.__currentSimulationTime = 0 self.__network = None self.__simulationProcessFactory = [] self.__resourcePeer = 0 self.__transactionNumber = 0 self.__transactionDateTimeStart = "" self.__transactionDateTimeStop = "" #self.__logger = SimulationLogger() #self.__logger.resgiterLoggingInfo("Create Simulation ") SimulationLogger().resgiterLoggingInfo("Create Simulation ") def initializeNetwork(self, peers ,newPeerTime ,neighbors): raise NotImplementedError() def addSimulationProcessFactory(self, simulationProcessFactory): if simulationProcessFactory in self.__simulationProcessFactory: return None simulationProcessFactory.setSimulation(self) simulationProcessFactory.initializeProcess() self.__simulationProcessFactory.append(simulationProcessFactory) return self.__simulationProcessFactory[self.__simulationProcessFactory.index(simulationProcessFactory)] def removeSimulationProcessFactory(self, simulationProcessFactory): if not simulationProcessFactory in self.__simulationProcessFactory: return None self.__simulationProcessFactory.remove(simulationProcessFactory) return simulationProcessFactory def getSimulationProcessFactorys(self): return self.__simulationProcessFactory def countSimulationProcessFactorys(self): return len(self.__simulationProcessFactory) def configure(self): raise NotImplementedError() def getNetwork(self): return self.__network def setNetwork(self, network): self.__network = network self.__network.setSimulation(self) return self.__network def getSimulationTime(self): return self.__simulationTime def setSimulationTime(self, simulationTime): self.__simulationTime = simulationTime return self.__simulationTime def getResourcePeer(self): return self.__resourcePeer def setResourcePeer(self, resourcePeer): self.__resourcePeer = resourcePeer return self.__resourcePeer def getTransactionNumber(self): return self.__transactionNumber def setTransactionNumber(self, number): self.__transactionNumber = number return self.__transactionNumber def getTransactionDateTimeStart(self): return self.__transactionDateTimeStart def setTransactionDateTimeStart(self, date): self.__transactionDateTimeStart = date return self.__transactionDateTimeStart def getTransactionDateTimeStop(self): return self.__transactionDateTimeStop def setTransactionDateTimeStop(self, date): self.__transactionDateTimeStop = date return self.__transactionDateTimeStop def getCurrentSimulationTime(self): semaphore = Semaphore() semaphore.acquire() time = self.__currentSimulationTime semaphore.release() return time def setCurrentSimulationTime(self, currentSimulationTime): semaphore = Semaphore() semaphore.acquire() self.__currentSimulationTime = currentSimulationTime semaphore.release() return self.__currentSimulationTime def getSimInstance(self): return self.__simInstance def start(self): mySim = self.getSimInstance() SimulationLogger().resgiterLoggingInfo("Start Simulation ") #Logger().resgiterLoggingInfo("Start Simulation ") factoryProcess = 0 for factory in self.__simulationProcessFactory: print factory.getName() mySim.activate( factory, factory.factorySimulationProcess(),at=factory.getActive()) factoryProcess +=1 mySim.simulate( until = self.getSimulationTime() ) return factoryProcess def stop(self): raise NotImplementedError() simInstance = property(getSimInstance, None, None, None) simulationTime = property(getSimulationTime, setSimulationTime, None, None) currentSimulationTime = property(getCurrentSimulationTime, setCurrentSimulationTime, None, None) network = property(getNetwork, setNetwork, None, None)
def __init__(self, resource, name="Experiment"): Simulation.__init__(self) self.name = name self.resource = resource self.scheduler = None
class RequestManagerTestCase(unittest.TestCase): # classes under test: DelayedRequest, ScheduledRequest def setUp(self): self.simulation = Simulation() self.simulation.initialize() self.obj1 = FakeClass(self.simulation) self.obj2 = FakeClass(self.simulation) def test_get_result_method1(self): r = self.obj1.method1(at=100, simulation=self.simulation) # or directly: r = self.fc.method1(100) self.simulation.simulate(1000) self.assertEquals(100, r.get_result()) def test_get_result_method2(self): r = self.obj1.method2(at=200, simulation=self.simulation, str_param="helloworld") self.simulation.simulate(1000) self.assertEquals((200, "helloworld"), r.get_result()) def test_scheduled_method1(self): self.obj1.method1(at=100) self.obj1.method1(at=300) self.obj2.method1(at=500) self.simulation.simulate(1000) self.assertItemsEqual( ( ("method1", 100), ("method1", 300) ), self.obj1.traces) self.assertItemsEqual( ( ("method1", 500), ), self.obj2.traces) def test_scheduled_method1(self): self.obj1.method1(at=100) self.obj1.method1(at=300) self.obj2.method1(at=500) self.simulation.simulate(1000) self.assertItemsEqual( ( ("method1", 100), ("method1", 300) ), self.obj1.traces) self.assertItemsEqual( ( ("method1", 500), ), self.obj2.traces) def test_scheduled_method2(self): self.obj1.method2(at=500, str_param="gato") self.obj1.method2(at=300, str_param="perro") self.obj2.method2(at=100, str_param="iguana") self.simulation.simulate(1000) self.assertItemsEqual( ( ("method2", 300, "perro"), ("method2", 500, "gato") ), self.obj1.traces) self.assertItemsEqual( ( ("method2", 100, "iguana"), ), self.obj2.traces) def test_scheduled_methods_all(self): self.obj1.method2(at=600, str_param="lagartija") self.obj1.method1(at=400) self.obj1.method2(at=500, str_param="gato") self.obj2.method1(at=300) self.obj2.method2(at=100, str_param="iguana") self.obj2.method2(at=200, str_param="salamandra") self.simulation.simulate(1000) self.assertItemsEqual( ( ("method1", 400), ("method2", 500, "gato"), ("method2", 600, "lagartija") ), self.obj1.traces) self.assertItemsEqual( ( ("method1", 300), ("method2", 100, "iguana"), ("method2", 200, "salamandra") ), self.obj2.traces) def test_normal_call(self): self.obj1.method2(str_param="before") self.simulation.simulate(1000) self.obj1.method2(str_param="after") # independent of simulation because no "simulation", "at" and "delay" are specified in both calls self.assertItemsEqual( ( ("method2", 0, "before"), ("method2", 0, "after") ), self.obj1.traces)
def __init__(self, configuration, callback=None): """ Args: - `callback`: A callback can be specified. This function will be \ called to report the advance of the simulation (useful for a \ progression bar). - `configuration`: The :class:`configuration \ <simso.configuration.Configuration>` of the simulation. Methods: """ Simulation.__init__(self) self._logger = Logger(self) task_info_list = configuration.task_info_list part_info_list = configuration.part_info_list proc_info_list = configuration.proc_info_list self._cycles_per_ms = configuration.cycles_per_ms self._time_partitioning = False self._donation_policy = configuration.donation_policy self._task_list = [] self._aborted_jobs = [] self._aborted_insts = [] self._aborted_jobs_times = {} self._aborted_insts_times = {} self._released_opt_jobs = 0 self._completed_opt_jobs = 0 self._released_opt_by_part = {} self._completed_opt_by_part = {} if(configuration.part_scheduler_info): self._time_partitioning = True self.part_scheduler = configuration.part_scheduler_info.instantiate(self) self.scheduler = None else: self.scheduler = configuration.scheduler_info.instantiate(self) self.scheduler.task_list = self._task_list try: self._etm = execution_time_models[configuration.etm]( self, len(proc_info_list) ) except KeyError: print("Unknowned Execution Time Model.", configuration.etm) for task_info in task_info_list: self._task_list.append(Task(self, task_info)) self._part_list = [] for part_info in part_info_list: self._part_list.append(TimePartition(self, part_info)) self._released_opt_by_part[part_info] = 0 self._completed_opt_by_part[part_info] = 0 # Init the processor class. This will in particular reinit the # identifiers to 0. Processor.init() # Initialization of the caches for cache in configuration.caches_list: cache.init() self._processors = [] for proc_info in proc_info_list: proc = Processor(self, proc_info) if(self._time_partitioning): proc.activate_time_partitioning(self.part_scheduler) for i in range(len(self._part_list)): if proc_info in part_info_list[i].cpus: self._part_list[i].cpus.append(proc) proc.caches = proc_info.caches self._processors.append(proc) # Now that processors have been added, init list of # interrupted jobs per partition for part in self._part_list: part.init_part() # XXX: too specific. self.penalty_preemption = configuration.penalty_preemption self.penalty_migration = configuration.penalty_migration self._etm.init() self._duration = configuration.duration self.progress = Timer(self, Model._on_tick, (self,), self.duration // 20 + 1, one_shot=False, in_ms=False) self._callback = callback # Add processors to either task scheduler or partition # scheduler if(self._time_partitioning): self.part_scheduler.processors = self._processors else: self.scheduler.processors = self._processors self.results = None
class TestCache(unittest.TestCase): def setUp(self): self.simulation = Simulation() self.browsing_subquery = SubQuery( name = "_services._dns-sd._udp.local", record_type = "PTR" ) self.sender = FakeSender(self.simulation) # used for the asserts self.querier = ContinuousQuerier(self.browsing_subquery, self.simulation, self.sender) self.querier._random = Mock() self.querier._random.random.side_effect = lambda *args: 0.5 self.simulation.initialize() self.simulation.activate(self.querier, self.querier.query_continuously()) def assert_contains_log(self, at, query_type="QM"): asserted = False for log_line in self.sender.log: if log_line[FakeSender.WHEN_FIELD] == at: self.assertEquals(query_type, log_line[FakeSender.QUERY_TYPE_FIELD]) self.assertEquals(self.browsing_subquery, log_line[FakeSender.SUBQUERY_FIELD]) asserted = True self.assertTrue(asserted) def test_query_continuously_one_query(self): self.simulation.simulate( until=20 + 100*0.5 + 1 ) self.assertEquals(1, len(self.sender.log)) self.assert_contains_log(20 + 100*0.5, "QU") def test_query_continuously_two_queries(self): self.simulation.simulate( until=20 + 100*0.5 + 1000 + 1 ) self.assertEquals(2, len(self.sender.log)) self.assert_contains_log(20 + 100*0.5, "QU") self.assert_contains_log(20 + 100*0.5 + 1000, "QM") def test_query_continuously_three_queries(self): self.simulation.simulate( until=20 + 100*0.5 + 1000 + 2000 + 1 ) self.assertEquals(3, len(self.sender.log)) self.assert_contains_log(20 + 100*0.5, "QU") self.assert_contains_log(20 + 100*0.5 + 1000, "QM") self.assert_contains_log(20 + 100*0.5 + 3000, "QM") def get_time_for_iteration_waiting_1hour(self): n = 1 # loops needed to reach to 60mins interval interval = 1000 acum_time = interval while interval<3600000: interval = interval * 2 if interval > 3600000: interval = 3600000 n += 1 acum_time += interval return acum_time, n def test_query_continuously_n_queries(self): t, n = self.get_time_for_iteration_waiting_1hour() self.simulation.simulate( until=20 + 100*0.5 + t + 1 ) self.assertEquals(n+1, len(self.sender.log)) # +1 for the 1st query! self.assert_contains_log(20 + 100*0.5 + t, "QM") self.assert_contains_log(20 + 100*0.5 + t - 3600000, "QM")
class RequestManagerTestCase(unittest.TestCase): # classes under test: DelayedRequest, ScheduledRequest def setUp(self): self.s = Simulation() self.s.initialize() self.request = FakeRequestInstance(sim=self.s) def test_NormalRequest(self): RequestManager.launchNormalRequest(self.request) self.s.simulate(100000) self.assertEquals(0, self.request.when) def test_DelayedRequest(self): RequestManager.launchDelayedRequest(self.request, 100) self.s.simulate(100000) self.assertEquals(100, self.request.when) # after 100 starting in 0 def test_cancel_DelayedRequest(self): RequestManager.launchDelayedRequest(self.request, 100) RequestManager.cancelRequest(self.request) self.s.simulate(100000) self.assertEquals(None, self.request.when) def test_ScheduledRequest(self): RequestManager.launchScheduledRequest(self.request, at=1000) self.s.simulate(100000) self.assertEquals(1000, self.request.when) # at 1000 def test_cancel_ScheduledRequest(self): RequestManager.launchScheduledRequest(self.request, 1000) RequestManager.cancelRequest(self.request) self.s.simulate(100000) self.assertEquals(None, self.request.when)
def _fixreactivate(self, *args, **kwargs): """Fix to make all reactivate() calls prior by default.""" if (len(args)<4) and ('prior' not in kwargs): # prior is not defined -> set to True kwargs['prior'] = True return Simulation.reactivate(self, *args, **kwargs)
def setUp(self): self.s = Simulation() self.s.initialize() self.request = FakeRequestInstance(sim=self.s)
def setUp(self): self.s = Simulation() self.s.initialize()
def __init__(self, seed): Simulation.__init__(self) self.rv = Random(seed)
class NewWPDetectorTestCase(unittest.TestCase): def setUp(self): self.simulation = Simulation() self.mdns_instance = Mock() self.mdns_instance.get_whitepage_record.return_value = None self.mdns_instance.notify_whitepage_changed.side_effect = self._log_event self.detector = NewWPDetector(self.mdns_instance, self.simulation) self.log = [] self.simulation.initialize() def _log_event(self): self.log.append(self.simulation.now()) # notification at def test_check_new_wps(self): self.simulation.activate(self.detector, self.detector.check_new_wps(), at = 0) s = WhitepageSetter(self.mdns_instance, "node0", self.simulation) self.simulation.activate(s, s.set_wp(), at = 1500) s = WhitepageSetter(self.mdns_instance, "node1", self.simulation) self.simulation.activate(s, s.set_wp(), at = 2500) self.simulation.simulate(until = 10000) self.assertEquals(2, len(self.log)) self.assertEquals(2000, self.log[0]) # when it does not discover a WP, it waits 1 secs self.assertEquals(7000, self.log[1]) # after discovering a it waits 5 secs
from SimPy.Simulation import (Simulation, Process, Resource, request, hold, release) """Object Oriented SimPy API""" # Model components ------------------------------- class Car(Process): def run(self, res): yield request, self, res yield hold, self, 10 yield release, self, res print("Time: %s" % self.sim.now()) # Model and Experiment --------------------------- s = Simulation() s.initialize() r = Resource(capacity=5, sim=s) auto = Car(sim=s) s.activate(auto, auto.run(res=r)) s.simulate(until=100)
def setUp(self): self.simulation = Simulation() self.simulation.initialize() self.proc1 = SimpleProcess(sim=self.simulation) self.proc2 = SimpleProcess(sim=self.simulation)
class TestCache(unittest.TestCase): def setUp(self): self.simulation = Simulation() self.cache = Cache(self.simulation) for i in range(5): at = i * 10 record = PTRRecord("_http._tcp.local", "name%d._http._tcp.local"%i, ) self.cache.records.append(record) self.cache.pending_events.append((at, Cache.EVENT_KNOWN_ANSWER, record)) record = SVRRecord("name%d._http._tcp.local"%i, None, None) self.cache.records.append(record) self.cache.pending_events.append((at, Cache.EVENT_KNOWN_ANSWER, record)) record = TXTRecord("name%d._http._tcp.local"%i, {}) self.cache.records.append(record) self.cache.pending_events.append((at, Cache.EVENT_RENEW, record)) self.assertEquals(15, len(self.cache.records)) self.assertEquals(15, len(self.cache.pending_events)) self.sample_txt = TXTRecord("name0._http._tcp.local", {}) self.sample_svr = SVRRecord("name2._http._tcp.local", None, None) self.sample_ptr = PTRRecord("_http._tcp.local", "name4._http._tcp.local") def does_contain_event(self, ttype, name, when=None, action=None): for event in self.cache.pending_events: cond = event is None or event[Cache.WHEN_FIELD]==when cond = cond and ( event is None or event[Cache.ACTION_FIELD]==action ) cond = cond and event[Cache.RECORD_FIELD].name == name cond = cond and event[Cache.RECORD_FIELD].type == ttype if cond: return True return False def test_get_known_answers(self): ka = self.cache.get_known_answers() # only records with action Cache.EVENT_KNOWN_ANSWER associated in pending_events self.assertEquals(10, len(ka)) self.assertFalse( self.sample_txt in ka ) self.assertTrue( self.sample_svr in ka ) self.assertTrue( self.sample_ptr in ka ) def test_delete_events_for_record(self): self.cache._delete_events_for_record(self.sample_txt) self.assertEquals(14, len(self.cache.pending_events)) self.assertFalse( self.does_contain_event(self.sample_txt.type, self.sample_txt.name) ) self.cache._delete_events_for_record(self.sample_svr) self.assertEquals(13, len(self.cache.pending_events)) self.assertFalse( self.does_contain_event(self.sample_svr.type, self.sample_svr.name) ) self.cache._delete_events_for_record(self.sample_ptr) self.assertEquals(12, len(self.cache.pending_events)) self.assertFalse( self.does_contain_event(self.sample_ptr.type, self.sample_ptr.name) ) def test_create_new_events(self): self.cache._random = Mock() self.cache._random.random.side_effect = lambda *args: 0.5 # 0.5 * 2% == 1% of variation self.cache.sim = Mock() self.cache.sim.now.side_effect = lambda: 0 self.sample_txt.ttl = 1 # to ease calculations self.cache._create_new_events(self.sample_txt) self.assertEquals(15+5, len(self.cache.pending_events)) self.assertTrue( self.does_contain_event(self.sample_txt.type, self.sample_txt.name, when=500, action=Cache.EVENT_KNOWN_ANSWER) ) self.assertTrue( self.does_contain_event(self.sample_txt.type, self.sample_txt.name, when=810, action=Cache.EVENT_RENEW) ) self.assertTrue( self.does_contain_event(self.sample_txt.type, self.sample_txt.name, when=860, action=Cache.EVENT_RENEW) ) self.assertTrue( self.does_contain_event(self.sample_txt.type, self.sample_txt.name, when=910, action=Cache.EVENT_RENEW) ) self.assertTrue( self.does_contain_event(self.sample_txt.type, self.sample_txt.name, when=960, action=Cache.EVENT_RENEW) ) def test_cache_record(self): new_record = copy.deepcopy(self.sample_txt) new_record.ttl = 1234 self.cache.cache_record(new_record) # substitutes 1 record, removes 1 event, adds 6 # already tested in test_delete_events_for_record and test_create_new_events self.assertEquals(15-1+5, len(self.cache.pending_events)) self.assertEquals(15, len(self.cache.records)) found = False for record in self.cache.records: if record.name == new_record.name and record.type == new_record.type: self.assertEquals( 1234, record.ttl ) # the cache contains the new version of the TXT record found = True break self.assertTrue(found) def test_wait_for_next_event(self): self.simulation.initialize() self.simulation.activate(self.cache, self.cache.wait_for_next_event()) self.simulation.simulate( until=90*60*1000 ) # simulate 90 mins self.assertEquals(0, len(self.cache.pending_events)) self.assertEquals(15, len(self.cache.records))