def test_calculate_loss_event2(self): """ Tests that event2 causes a loss of 250 """ event = Event('flood', 'Louisiana', 500, deals) loss = event.total_loss() assert loss == 250
def test_calculate_loss_event4(self): """ Tests that event4 causes a loss of 1250. Tests when an event affects more than 1 deal. """ event = Event('hurricane', 'Florida', 2000, deals) loss = event.total_loss() assert loss == 1250
def test_calculate_loss_event1(self): """ Tests that event1 causes a loss of 500 """ event = Event('earthquake', 'California', 1000, deals) loss = event.total_loss() assert loss == 500
def test_calculate_loss_event3(self): """ Tests that event3 causes a loss of 250 """ event = Event('flood', 'Florida', 750, deals) loss = event.total_loss() assert loss == 250
def test_add_new_peril_to_existing_deal_and_calculate_loss(self): """ Tests that a new peril can be added dynamically to an existing deal for an uncovered event and the loss can be calculated on the fly. Also tests that is the damage is lower then the retention, then the loss is 0 """ peril = 'fire' region = 'Porto' damage = 400 event = Event(peril, region, damage, deals) if not event.deals_list: ManageDeals.add_new_deal(250, 250, [ peril, ], [ region, ], deals) peril = 'fire' region = 'Lisbon' damage = 700 event = Event(peril, region, damage, deals) if not event.deals_list: ManageDeals.add_region_to_deal('deal4', region, deals) peril = 'draught' region = 'Lisbon' damage = 100 event = Event(peril, region, damage, deals) if not event.deals_list: ManageDeals.add_peril_to_deal('deal4', peril, deals) event.get_applicable_deals(deals) loss = event.total_loss() assert loss == 0
def test_get_applicable_deals_returns_list_with_1_deal(self): event = Event('flood', 'Louisiana', 500, deals) event.deals_list = [] event.get_applicable_deals(deals) self.assertAlmostEqual(event.deals_list, [{ 'retention': 250, 'limit': 250, 'perils': ['hurricane', 'flood'], 'regions': ['Florida', 'Louisiana'] }])
def test_get_applicable_deals_returns_list_with_2_deal(self): event = Event('hurricane', 'Florida', 2000, deals) event.deals_list = [] event.get_applicable_deals(deals) self._baseAssertEqual(event.deals_list, [{ 'regions': ['Florida', 'Louisiana'], 'perils': ['hurricane', 'flood'], 'limit': 250, 'retention': 250 }, { 'regions': ['Florida'], 'perils': ['hurricane'], 'limit': 3000, 'retention': 1000 }])
async def async_dispatch(self, event: Event): """Dispatches an event on the bus""" if not event.context.authorize(scopes.BUS, scopes.WRITE): return listeners = [] for fragment in event.walk_path(): listeners += self._listeners.get(fragment, []) # getting top level matches listeners += self._listeners.get(f"{fragment}.*", []) listeners += self._listeners.get(events.MATCH_ALL, []) if event.event_type not in silent_events: LOGGER.info(event) for handler in listeners: if len(inspect.signature(handler).parameters) == 2: self.core.add_job(handler, event, event.context) else: self.core.add_job(handler, event) await self._event_stream.put(event)
async def set_volume(self, volume): self.core.bus.dispatch(Event("cec.setting_volume", volume)) running = True if self._target is not None else False self._target = volume if not running: await self.out_queue.put( Command(CECCommand.get_volume, self._approach_volume) )
def test_add_new_deal_and_calculate_loss(self): """ Tests that a new deal can be added dynamically for an uncovered event and the loss can be calculated on the fly """ peril = 'fire' region = 'Porto' damage = 400 event = Event(peril, region, damage, deals) if not event.deals_list: ManageDeals.add_new_deal(250, 250, [ peril, ], [ region, ], deals) event.get_applicable_deals(deals) loss = event.total_loss() assert loss == 150
async def prepare(self): await self.websocket.prepare(self.request) self.is_open = True self.core.bus.dispatch( Event( NEW_WEBSOCKET_CONNECTION, { "id": self.id, "type": self.connection_type, "connection": self }, )) self.core.add_job(self.reader) await self.writer()
async def dispatch_event_service(self, content: Any, context: Context, event_type: str = ""): """ dispatch an event on the event bus :param content: :param context: :param event_type: :return: """ if context.authorize(BUS, DISPATCH_EVENT): event = Event(event_type, content, context) self.dispatch(event) else: raise NotAuthorizedError( f"user {context.user} is not allowed to access the bus", context, BUS)
async def cio(self): while True: with suppress(Exception): _input = await ainput() args = _input.split(" ") if args[0] in ["run", "r"]: if len(args) == 4: config = ast.literal_eval(args[3]) else: config = {} self.io.run_service(args[1], ast.literal_eval(args[2]), config, Context.admin()) elif args[0] in ["set", "s"]: self.registry.call_method_d(f"{args[1]}.set", ast.literal_eval(args[2]), Context.admin()) elif args[0] in ["dispatch", "d"]: self.bus.dispatch(Event(args[1], ast.literal_eval(args[2])))
def disconnected(self, e): self.instance.close() if self.reconnect and not self.silent: LOGGER.warning( f"Serial port {self.port} disconnected. Exception: {e}. Trying to reconnect in {self.reconnect_time}" ) elif not self.silent: LOGGER.warning( f"Serial port {self.port} disconnected. Exception: {e}.") self.core.bus.dispatch( Event(constants.Events.port_disconnected, { "port": self.port, "name": self.name, "exception": e })) if self.reconnect: self.core.timer.scheduled_call(self.setup, delay=self.reconnect_time)
def dispatch_state_change_event( self, entity: Entity, component: str, new_state: Any, executing_context: Context, context: Context = None, ): self.core.bus.dispatch( Event( event_type=ENTITY_STATE_CHANGED, event_content={ "entity": entity, "component": component, "new_state": new_state, "component_type": entity.components[component].type, "executing_context": executing_context, }, context=context, ))
async def manager(self, reader, writer: StreamWriter): self.core.bus.dispatch( Event(event_type="cec.reconnected", event_content=None, context=None) ) while True: try: done, pending = await asyncio.wait( [self.out_queue.get(), reader.readline(), self._close_event.wait()], return_when=asyncio.FIRST_COMPLETED, loop=self.core.event_loop, ) except Exception as e: print(e) break try: gathered = asyncio.gather(*pending) gathered.cancel() await gathered except CancelledError: pass result = done.pop().result() if type(result) is bool: writer.close() await writer.wait_closed() self._closed_event.set() break if type(result) is Command: if type(result.command.value) is list: for fragment in result.command.value: writer.write(fragment.encode()) else: writer.write(result.command.value.encode()) await writer.drain() if result.callback: msg = await reader.readline() await result.callback(msg.decode()) else: pass
async def _approach_volume(self, new_volume): if str(new_volume).startswith("51:7a:"): self.volume = calculate_volume(new_volume) elif type(new_volume) is str: await self.out_queue.put( Command(CECCommand.get_volume, self._approach_volume) ) return await asyncio.sleep(0.2) if self._target < self.volume: await self.out_queue.put( Command(CECCommand.decrease_volume, self._approach_volume) ) elif self._target > self.volume: await self.out_queue.put( Command(CECCommand.increase_volume, self._approach_volume) ) else: self._target = None self.core.bus.dispatch(Event("cec.set_volume", self.volume))
async def setup(self, time=None): try: self.instance.close() except: pass try: self.instance.open() except Exception as e: if not self.silent: LOGGER.warning( f"couldn't open serial port {self.port}! Exceptions {e}") if self.reconnect: self.core.timer.scheduled_call(self.setup, delay=self.reconnect_time) return self.__reader = self.core.add_job(self._reader) self.__writer = self.core.add_job(self._writer) self.core.bus.dispatch( Event(constants.Events.port_connected, { 'port': self.port, 'name': self.name }))
def test_total_loss_limited_by_limit(self): event = Event('flood', 'Louisiana', 450000, deals) self.assertTrue(event.total_loss() == 250)
def created_event(entity: Entity, user: User): return Event( event_type=ENTITY_CREATED, event_content=entity, context=Context(user=user, remote=False), )
async def gql_dispatch_event(self, *_, eventType="", eventContent=None): self.core.bus.dispatch( Event(event_type=eventType, event_content=eventContent))
def playback_device_change(device: asp.Device): return Event(event_type=EVENT_PLAYBACK_DEVICE_CHANGE, event_content=device)
def test_total_loss_lower_then_limit(self): event = Event('flood', 'Louisiana', 450, deals) self.assertTrue(event.total_loss() == 200)
def playback_started_event(track: asp.track.FullTrack): return Event(event_type=EVENT_PLAYBACK_STARTED, event_content=track)
def track_change_event(track: asp.track.FullTrack): return Event(event_type=EVENT_TRACK_CHANGE, event_content=track)
def playback_resumed_event(track: asp.track.FullTrack): return Event(event_type=EVENT_PLAYBACK_RESUMED, event_content=track)
def playback_stopped_event(track: Optional[asp.track.FullTrack]): return Event(event_type=EVENT_PLAYBACK_STOPPED, event_content=track)
def test_total_loss_returns_0_when_damage_lower_then_retention(self): event = Event('flood', 'Louisiana', 100, deals) self.assertTrue(event.total_loss() == 0)
def test_total_loss_returns_0_with_several_deals_when_damage_lower_the_retetion( self): event = Event('hurricane', 'Florida', 50, deals) self.assertTrue(event.total_loss() == 0)
def test_total_loss_returns_0_when_no_deal_exists_for_event(self): event = Event('hurricane', 'Minnesota', 2000, deals) event.deals_list = [] self.assertTrue(event.total_loss() == 0)