def test_only_one_execution(self): dispatcher = EventDispatcher() func = lambda x: x.name dispatcher.add('SampleEvent', func, only_once=True) result = dispatcher.trigger(Event('SampleEvent')) assert len(result) == 1 result2 = dispatcher.trigger(Event('SampleEvent')) assert len(result2) == 0
def __create_instance(self, name, definition): params = {'definition': definition, 'dependency': name} pre_process_event = Event(name=PRE_EVENT, target=definition, params=params) result = self.dispatcher.trigger(pre_process_event) dependency = result.last() post_process_event = Event(name=POST_EVENT, target=dependency, params=params) self.dispatcher.trigger(post_process_event) return dependency
def run(self, environ, start_response): request = create_request_from_environ( environ, self.config['session']['class'], self.config['session'].get('options')) try: route_result = self.dispatcher.trigger( Event(events.ROUTE_MATCH, target=self, params={ 'request': request, 'router': self.container.get('router') })) route_match = route_result.first() except ApplicationError as exc: route_match = None response, view_model = self.__raise_exception_event( exception=exc, request=request) if route_match: try: dispatch_event = Event(events.DISPATCH_EXECUTE, target=self, params={ 'route_match': route_match, 'request': request, 'container': self.container }) dispatch_result = self.dispatcher.trigger(dispatch_event) response = dispatch_event.params['controller_class'].response view_model = dispatch_result.first() except ApplicationError as exc: response, view_model = self.__raise_exception_event( exception=exc, request=request, route_match=route_match) if not isinstance(view_model, Response): try: self.__render(request=request, response=response, view_model=view_model) except ApplicationError as exc: response, view_model = self.__raise_exception_event( exception=exc, request=request, route_match=route_match) self.__render(request=request, response=response, view_model=view_model) start_response(*response.start()) self.dispatcher.trigger( Event(events.COMPLETE, target=self, params={'container': self.container})) return [response()]
def run(self, environ, start_response): request = Request.from_environ( environ, session_class=self.config['session'].get('class', None), session_options=self.config['session'].get('options', None)) context = {'request': request} self.context = context # Retrieve the required route match for the request. try: route_result = self.dispatcher.trigger( Event(events.ROUTE_MATCH, target=self, params={ 'context': context, 'router': self.container.get('router') })) route_match = route_result.first() except ApplicationError as exc: route_match = None response, view_model = self.exception(exception=exc, context=context) # Execute the relevant controller for the route if route_match: try: dispatch_result = self.dispatcher.trigger( Event(events.DISPATCH_EXECUTE, target=self, params={ 'container': self.container, 'context': context })) response, view_model = dispatch_result.first() except ApplicationError as exc: response, view_model = self.exception(exception=exc, context=context) # Render the view model or response if not hasattr(view_model, 'status_code'): try: self.render(context=context, view_model=view_model) except Exception as exc: response, view_model = self.exception(exception=exc, context=context) # Do any cleanup required after the request has ended self.dispatcher.trigger( Event(events.COMPLETE, target=self, params={'container': self.container})) return response(start_response)
def __init__(self, config=None): """Initializes the application. Registers any events that are within the application configuration. Usage: app = Base() Events: Dispatches the INIT. Args: mixed config: See the Base.config properties. """ self.config = config or {} self.dispatcher = self.container.get('shared_event_dispatcher') for event, listeners in self.config['events'].items(): for callback_priority_pair in listeners: try: priority = callback_priority_pair.priority except: priority = 1 try: once_only = callback_priority_pair.once_only except: once_only = False self.dispatcher.add( event, self.container.get(callback_priority_pair[0]), priority, once_only) self.dispatcher.trigger(Event(events.INIT, target=self)) super(Base, self).__init__()
def test_execute(self): with raises(InternalServerError): route = LiteralRoute('test', path='/') match = RouteMatch(route, {}) event = Event('something', params={'context': {'route_match': match}}) listener = listeners.DispatchExecute({'404': 'page/404'}) listener(event)
def render(self, with_dispatcher=True, **kwargs): kwargs['container'] = self.container render_event = Event(events.RENDER_VIEW, target=self, params=kwargs) if with_dispatcher: self.dispatcher.trigger(render_event) else: listener = self.container.get('app_render_listener') listener(render_event)
def sample_event(target): definition = { 'item': target, } return Event('Sample', params={ 'definition': definition }, target=definition)
def __run_inner(self, request): context = { 'request': request } self.context = context # Retrieve the required route match for the request. try: route_result = self.dispatcher.trigger( Event( events.ROUTE_MATCH, target=self, params={'context': context, 'router': self.container.get('router')})) route_match = route_result.first() except self.exception_class as exc: route_match = None response, view_model = self.exception(exception=exc, context=context) # Execute the relevant controller for the route if route_match: try: dispatch_result = self.dispatcher.trigger( Event( events.DISPATCH_EXECUTE, target=self, params={'container': self.container, 'context': context})) response, view_model = dispatch_result.first() except self.exception_class as exc: response, view_model = self.exception( exception=exc, context=context) # Render the view model or response if not hasattr(view_model, 'status_code'): try: self.render(context=context, view_model=view_model) except Exception as exc: response, view_model = self.exception(exception=exc, context=context) # Do any cleanup required after the request has ended self.dispatcher.trigger(Event(events.COMPLETE, target=self, params={'container': self.container})) return response
def create_event(self, **kwargs): router = DictRouter({'home': {'path': '/'}}) environ = {} util.setup_testing_defaults(environ) environ.update(**kwargs) context = {'request': Request.from_environ(environ)} event = Event( 'TestEvent', params={'router': router, 'context': context}) return event
def create_event(self, **kwargs): router = Router({'home': {'path': '/'}}) environ = {} util.setup_testing_defaults(environ) environ.update(**kwargs) event = Event('TestEvent', params={ 'router': router, 'request': create_request_from_environ(environ) }) return event
def test_stopped_propagation(self): dispatcher = EventDispatcher() def func(event): event.stop_propagation() return event.name func2 = lambda x: x.name dispatcher.add('SampleEvent', func) dispatcher.add('SampleEvent', func2) result = dispatcher.trigger(Event('SampleEvent')) assert len(result) == 1
def test_short_circuit(self): environ = sample_environ() route = LiteralRoute( 'test', path='/', options={'controller': 'tests.watson.framework.support.ShortCircuitedController'}) match = RouteMatch(route, {}) context = {'request': Request.from_environ(environ), 'route_match': match} event = Event( 'something', params={'container': IocContainer(), 'context': context}) listener = listeners.DispatchExecute({'404': 'page/404'}) response, view_model = listener(event) assert isinstance(response, Response)
def test_overriden_template(self): environ = sample_environ() route = LiteralRoute( 'test', path='/', options={'controller': 'tests.watson.framework.support.SampleActionController'}) match = RouteMatch(route, {'action': 'view_model_template'}) context = {'request': Request.from_environ(environ), 'route_match': match} event = Event( 'something', params={'container': IocContainer(), 'context': context}) listener = listeners.DispatchExecute({'404': 'page/500'}) response, view_model = listener(event) assert isinstance(view_model, views.Model) assert view_model.template == 'sampleactioncontroller/404'
def exception(self, last_exception=None, **kwargs): event = Event(events.EXCEPTION, target=self, params=kwargs) result = self.dispatcher.trigger(event) view_model = result.first() response = Response(kwargs['exception'].status_code) context = kwargs['context'] context['response'] = response if last_exception: self.render(with_dispatcher=False, view_model=view_model, context=context) try: self.render(view_model=view_model, context=context) except Exception as exc: kwargs['exception'] = exc self.exception(last_exception=exc, **kwargs) return response, view_model
def test_execute(self): app = applications.Http() listener = listeners.Render(config.views) context = { 'response': Response(200), } vm = views.Model(format='text/plain', data={'content': 'test'}) params = {'context': context, 'view_model': vm, 'container': app.container} event = Event('render', params=params) # error raised as no template exists with raises(InternalServerError): listener(event) with raises(InternalServerError): vm.format = 'exe' listener(event) vm.format = 'json' response = listener(event) assert response.status_code == 200 assert response.headers['Content-Type'] == 'application/json'
def test_short_circuit(self): environ = sample_environ() route = Route('test', path='/', options={ 'controller': 'tests.watson.mvc.support.ShortCircuitedController' }) match = RouteMatch(route, { 'controller': 'tests.watson.mvc.support.ShortCircuitedController' }) event = Event('something', params={ 'route_match': match, 'container': IocContainer(), 'request': create_request_from_environ(environ) }) listener = listeners.DispatchExecute({'404': 'page/404'}) response = listener(event) assert isinstance(response, Response)
def exception(self, last_exception=None, **kwargs): event = Event(events.EXCEPTION, target=self, params=kwargs) result = self.dispatcher.trigger(event) view_model = result.first() response = Response(kwargs['exception'].status_code) context = kwargs['context'] accept = context['request'].headers.get('accept') if accept: accept_parts = accept.split('/') if len(accept_parts) > 1: view_model.format = accept_parts[1] context['response'] = response if last_exception: self.render(with_dispatcher=False, view_model=view_model, context=context) try: self.render(view_model=view_model, context=context) except Exception as exc: # Triggered when an exception occurs rendering the exception kwargs['exception'] = exc self.exception(last_exception=exc, **kwargs) return response, view_model
def test_stop_propagation(self): event = Event('SampleEvent') assert event.stopped == False event.stop_propagation() assert event.stopped == True
def __render(self, **kwargs): kwargs['container'] = self.container render_event = Event(events.RENDER_VIEW, target=self, params=kwargs) self.container.add('render_event_params', kwargs) self.dispatcher.trigger(render_event)
def __raise_exception_event(self, **kwargs): exception_event = Event(events.EXCEPTION, target=self, params=kwargs) exception_result = self.dispatcher.trigger(exception_event) return Response( kwargs['exception'].status_code), exception_result.first()
def test_trigger(self): dispatcher = EventDispatcher() func = lambda x: x.name dispatcher.add('SampleEvent', func) result = dispatcher.trigger(Event('SampleEvent')) assert result.first() == 'SampleEvent'
def test_add_remove_params(self): event = Event('SampleEvent') event.params['test'] = 'test' assert event.params['test'] == 'test' del event.params['test'] assert 'test' not in event.params
def test_set_valid_params(self): event = Event('SampleEvent', params={'test': 'test'}) assert event.params['test'] == 'test'
def test_set_invalid_params(self): Event('SampleEvent', params='test')
def test_event_target(self): event = Event('SamplEvent', target=self) assert event.target == self
def test_stop_propagation(self): event = Event('SampleEvent') assert event.stopped is False event.stop_propagation() assert event.stopped
def test_execute(self): route = Route('test', path='/') match = RouteMatch(route, {}) event = Event('something', params={'route_match': match}) listener = listeners.DispatchExecute({'404': 'page/404'}) listener(event)
def test_create_event(self): assert repr(Event(name='SampleEvent') ) == '<watson.events.types.Event name:SampleEvent>'
def trigger_init_event(self): """Execute any event listeners for the INIT event. """ self.dispatcher.trigger(Event(events.INIT, target=self))