def bind(self, service_locator: ServiceLocator): for registration in self.registry.get_annotated_in_package( EventHandler, self.root_package): if registration.is_class_registration() and issubclass( registration.registered, Runnable): runner_class = registration.registered service_locator.bind(runner_class, runner_class)
class AbstractContext(object): INSTANCE: "AbstractContext" = None def __init__(self): self.serviceLocator = ServiceLocator() AbstractContext.INSTANCE = self self.serviceLocator.bind(ServiceLocator, self.serviceLocator) def configure_service_locator(self): raise NotImplementedError def service_locator(self) -> ServiceLocator: return self.serviceLocator def get_views_folder_path(self) -> str: raise NotImplementedError def get_config_file_locations(self) -> List[str]: raise NotImplementedError def create_router_config(self) -> RouterBuilder: raise NotImplementedError def get_banner(self) -> List[str]: return """ _ _ | (_) | |___ ____ _ __ _ ___ _ | | \ \ / / _` |/ _` |/ _ \ | |__| | |\ V / (_| | (_| | (_) | \____/|_| \_/ \__,_|\__, |\___/ __/ | |___/ """.split("\n")
def setUp(self): self.service_locator = ServiceLocator() self.service_locator.bind(SomeScheduledTask, SomeScheduledTask) self.service_locator.bind(SomeCrashingTask, SomeCrashingTask) self.service_locator.bind(SomeTaskCrashingOnCleanup, SomeTaskCrashingOnCleanup) self.schedule_mock: Schedule = mock.create_autospec(Schedule) self.schedule_mock.next_start_time.return_value = datetime.now()
def build(self, registry: Registry, service_locator: ServiceLocator) -> Router: cors_handler = CorsHandler(self.cors_rules) service_locator.bind(CorsHandler, cors_handler) filter_chain_factory = FilterChainFactory( self.filtering_rules, service_locator, RouteHandlerFactory(service_locator, Deserializer(registry), self.routing_rules, cors_handler)) return Router(service_locator, RequestFactory(), filter_chain_factory)
def test_givenSavedFilterClass_whenGettingFilters_thenGetInstanceFromServiceLocator(self): rule = FilteringRule("/*", [Filter]) service_locator = ServiceLocator() filter_instance = object() service_locator.bind(Filter, filter_instance) filters = rule.get_filters(service_locator) self.assertEqual(1, len(filters)) self.assertEqual(filter_instance, filters[0])
def setUp(self): self.serviceLocator = ServiceLocator() self.serviceLocator.bind(ResourceClass, ResourceClass) registry = Registry() self.routingTable = ReflectiveRoutingTable( registry, [Registration(ResourceClass, arguments={"value": PATH})]) self.deserializer = Deserializer(registry) self.resource_invocator = TestIntegratedResourceInvoker( self.serviceLocator, self.routingTable, self.deserializer) self.request = Request('GET', PATH, {}, "", "") ResourceClass.has_been_called = False
class JitMessageDispatcherClassTest(unittest.TestCase): def setUp(self): self.service_locator = ServiceLocator() self.service_locator.bind(DispatcherMock, DispatcherMock) def test_whenHandlingMessage_thenInstantiateAndInvoke(self): message_dispatcher_class = JitMessageDispatcherClass( MESSAGE_NAME, DispatcherMock, DispatcherMock.handle_message, self.service_locator) result = message_dispatcher_class.handle(PAYLOAD) self.assertEqual(PAYLOAD, result)
class MessageDispatcherRunnableTest(unittest.TestCase): def setUp(self): self.service_locator = ServiceLocator() self.dependency_mock = mock.MagicMock() self.service_locator.bind(object, self.dependency_mock) self.service_locator.bind(MessageDispatcherRunnableMock, MessageDispatcherRunnableMock) def test_whenHandlingMessage_thenInstantiateAndCallRunMethod(self): dispatcher = MessageDispatcherRunnable("foo", MessageDispatcherRunnableMock, self.service_locator) dispatcher.handle(None) self.dependency_mock.assert_called()
def test_givenFilterInstance_whenGettingFilters_thenReturnFilterInstanceAsIs(self): instance = mock.create_autospec(Filter) rule = FilteringRule("/*", [instance]) filters = rule.get_filters(ServiceLocator()) self.assertEqual(1, len(filters)) self.assertEqual(instance, filters[0])
def setUp(self): self.routing_table = TreeRoutingTable() self.routing_table.register_route(GET, PATH, RESOURCE_CLASS, ROUTE_METHOD) self.route_handler_factory = RouteHandlerFactory( ServiceLocator(), Deserializer(Registry()), [RoutingRule("/", self.routing_table)], CorsRequestHandlerFactory([CorsRule("/", {})])) self.request_builder = RequestBuilder().method("GET").path(PATH)
class AnnotatedClassBinderTest(unittest.TestCase): def setUp(self): self.service_locator = ServiceLocator() self.registry = Registry() self.binder = AnnotatedClassBinder("", self.registry, _binding_annotation) def test_whenBinding_thenBindAllAnnotatedClassesToThemselves(self): self.binder.bind(self.service_locator) instance = self.service_locator.get(SomeComponent) self.assertIsInstance(instance, SomeComponent)
class RunnableEventHandlerBinderTest(unittest.TestCase): def setUp(self): self.registry = Registry() self.service_locator = ServiceLocator() def test_whenConfiguringServiceLocator_thenFindAnnotatedEventHandlerRunnableClasses( self): RunnableEventHandlerBinder("", self.registry).bind(self.service_locator) instance = self.service_locator.get(_RunnableHandler) self.assertIsInstance(instance, _RunnableHandler)
def test_givenPrefixedRule_whenCreatingRouteHandlers_thenCreateResourceInvokerWithTruncatedPathForEveryRoute( self): request = self.request_builder.path("/prefix" + PATH).build() rule = RoutingRule("/prefix", self.routing_table) self.route_handler_factory = RouteHandlerFactory( ServiceLocator(), Deserializer(Registry()), [rule], CorsHandler([CorsRule("/", {})])) handlers: List[PathRewritingRouteHandlerDecorator] = [ x for x in self.route_handler_factory.create_route_handlers(request) ] self.assertEqual(1, len(handlers)) self.assertEqual(PATH, handlers[0].new_path)
class ScheduledTaskRunnerTests(unittest.TestCase): def setUp(self): self.service_locator = ServiceLocator() self.service_locator.bind(SomeScheduledTask, SomeScheduledTask) self.service_locator.bind(SomeCrashingTask, SomeCrashingTask) self.service_locator.bind(SomeTaskCrashingOnCleanup, SomeTaskCrashingOnCleanup) self.schedule_mock: Schedule = mock.create_autospec(Schedule) self.schedule_mock.next_start_time.return_value = datetime.now() def test_run_scheduled_task(self): self.runner = ScheduledTaskRunner(SomeScheduledTask, self.schedule_mock, self.service_locator) self.runner.start() self.assertTrue(SomeScheduledTask.was_called) def test_givenUncaughtException_whenExecuting_shouldNotCrash(self): self.runner = ScheduledTaskRunner(SomeCrashingTask, self.schedule_mock, self.service_locator) self.runner.start() time.sleep(0.05) self.assertTrue(SomeCrashingTask.times_called > 1) def test_givenUncaughtException_whenCleaningUp_shouldNotCrash(self): self.runner = ScheduledTaskRunner(SomeTaskCrashingOnCleanup, self.schedule_mock, self.service_locator) self.runner.start() self.runner.stop() self.assertTrue(SomeTaskCrashingOnCleanup.run_called) self.assertTrue(SomeTaskCrashingOnCleanup.cleanup_called) def tearDown(self): self.runner.stop()
def setUp(self): self.registry = Registry() self.service_locator = ServiceLocator()
def setUp(self): self.serviceLocator = ServiceLocator(Registry())
class ServiceLocatorTest(unittest.TestCase): A_LITERAL_OBJECT = "A Message" def setUp(self): self.serviceLocator = ServiceLocator(Registry()) def test_givenInexistentComponent_whenGettingComponent_thenThrowInstantiationException( self): with self.assertRaises(InstantiationException): self.serviceLocator.get(SomeClass) def test_givenLiteralComponent_whenGettingComponent_thenReturnsLiteralWithoutInstantiation( self): self.serviceLocator.bind(str, self.A_LITERAL_OBJECT) component = self.serviceLocator.get(str) self.assertEqual(self.A_LITERAL_OBJECT, component) def test_givenInstantiatableComponent_whenGettingComponent_thenReturnInstantiatedObject( self): self.serviceLocator.bind(SomeClass, SomeClass) component = self.serviceLocator.get(SomeClass) self.assertIsInstance(component, SomeClass) def test_givenBoundAbstraction_whenGettingChildComponent_thenReturnChildComponent( self): self.serviceLocator.bind(SomeClass, SomeChildClass) component = self.serviceLocator.get(SomeClass) self.assertIsInstance(component, SomeChildClass) def test_givenConstructorWithParameters_whenGettingComponent_thenRecursivelyInstantiateConstructorParameters( self): self.serviceLocator.bind(SomeClassWithParameters, SomeClassWithParameters) self.serviceLocator.bind(SomeClass, SomeClass) component = self.serviceLocator.get(SomeClassWithParameters) self.assertIsInstance(component, SomeClassWithParameters) self.assertIsInstance(component.someObject, SomeClass) def test_givenProviderMethodWithParameters_whenGettingComponent_thenCallProviderMethodWithRecursivelyInstantiatedParameters( self): self.serviceLocator.bind(SomeChildClass, provider_function_with_parameters) self.serviceLocator.bind(SomeClass, SomeClass) component = self.serviceLocator.get(SomeChildClass) self.assertIsInstance(component, SomeChildClass) def test_givenScopedComponent_whenGettingComponentTwice_thenReturnTheSameComponentTwice( self): scope_cache = SingletonScopeCache(Singleton, [SomeClass]) self.serviceLocator.register_scope(scope_cache) self.serviceLocator.bind(SomeClass, SomeClass) expected = self.serviceLocator.get(SomeClass) result = self.serviceLocator.get(SomeClass) self.assertIsInstance(expected, SomeClass) self.assertEqual(expected, result) def test_givenClassWithNonInjectableConstructor_whenGettingComponent_thenThrowNonInjectableConstructorException( self): self.serviceLocator.bind(SomeClassWithANonInjectableConstructor, SomeClassWithANonInjectableConstructor) with self.assertRaises(NonInjectableConstructorException): self.serviceLocator.get(SomeClassWithANonInjectableConstructor) def test_givenNonInjectableConstructorWithOnlyOneParameter_whenGettingComponent_thenInstantiateTheComponentAnyway( self): self.serviceLocator.bind(ClassWithImplicitlyInjectableConstructor, ClassWithImplicitlyInjectableConstructor) component = self.serviceLocator.get( ClassWithImplicitlyInjectableConstructor) self.assertIsInstance(component, ClassWithImplicitlyInjectableConstructor) def test_givenAConstructorWhichContainsAFunctionDefinition_whenGettingComponent_thenComponentIsInstantiatedWithoutInterferingWithTheFunction( self): self.serviceLocator.bind(ClassWhichContainsAFunctionInItsConstructor, ClassWhichContainsAFunctionInItsConstructor) self.serviceLocator.bind(SomeClass, SomeClass) component = self.serviceLocator.get( ClassWhichContainsAFunctionInItsConstructor) self.assertIsInstance(component, ClassWhichContainsAFunctionInItsConstructor) def test_givenAProviderFunctionWithAnotherFunctionDefinedInsideIt_whenGettingComponent_thenComponentIsInstantiatedWithoutInterferingWithTheInnerFunction( self): self.serviceLocator.bind( SomeChildClass, function_with_another_function_defined_inside_it) self.serviceLocator.bind(SomeClassWithParameters, SomeClassWithParameters) self.serviceLocator.bind(SomeClass, SomeClass) component = self.serviceLocator.get(SomeChildClass) self.assertIsInstance(component, SomeChildClass) def test_givenList_whenGettingComponent_thenReturnAllInstancesOfClass( self): self.serviceLocator.bind(SomeClass, SomeClass) self.serviceLocator.bind(SomeChildClass, SomeChildClass) components = self.serviceLocator.get(List[SomeClass]) self.assertEqual(2, len(components)) self.assertTrue( Stream(components).allMatch(lambda c: isinstance(c, SomeClass))) def test_whenManuallyInstantiatingAnInjectable_thenPassSelfVariableAndDoNotCrash( self): # Injectable should not interfere with the base class # fix crash on version 0.0.9 obj = SomeClassWithParameters(None) self.assertIsInstance(obj, SomeClassWithParameters)
def setUp(self): self.service_locator = ServiceLocator() self.service_locator.bind(DispatcherMock, DispatcherMock)
def setUp(self): self.serviceLocator = ServiceLocator() self.result = [] self.serviceLocator.bind = lambda interface, implementation: self.result.append( (interface, implementation))
def bind(self, service_locator: ServiceLocator): for registration in self.registry.get_annotated_in_package(self.annotation, self.rootPackage): component = registration.registered service_locator.bind(component, component)
class IntegratedResourceInvokerTest(unittest.TestCase): def setUp(self): self.serviceLocator = ServiceLocator() self.serviceLocator.bind(ResourceClass, ResourceClass) registry = Registry() self.routingTable = ReflectiveRoutingTable( registry, [Registration(ResourceClass, arguments={"value": PATH})]) self.deserializer = Deserializer(registry) self.resource_invocator = TestIntegratedResourceInvoker( self.serviceLocator, self.routingTable, self.deserializer) self.request = Request('GET', PATH, {}, "", "") ResourceClass.has_been_called = False def test_whenInvoking_thenGetsCorrespondingResourceInRoutingTable(self): self.resource_invocator.invoke(self.request) self.assertTrue(ResourceClass.has_been_called) def test_givenRouteWhichRequiresARequestObject_whenInvoking_thenInvokeTheRouteWithTheRequestObject( self): self.request.path += "/request" self.resource_invocator.invoke(self.request) # Assert is done in the route method below def test_givenRouteWhichReturnsResponse_whenInvoking_thenDirectlyReturnTheRouteResponse( self): response = self.resource_invocator.invoke(self.request) self.assertIsInstance(response, Response) def test_givenRouteWhichReturnsSomethingOtherThanAResponse_whenInvoking_thenReturnValueIsSavedInTheBodyOfTheResponse( self): response = self.resource_invocator.invoke(self.request) self.assertEqual(ResourceClass().a_method(), response.body) def test_givenRouteWhichReturnsSomethingOtherThanAResponse_whenInvoking_thenResponseHas200OkStatus( self): response = self.resource_invocator.invoke(self.request) self.assertEqual(200, response.status) def test_givenRouteWhichTakesADictionaryAsParameter_whenInvoking_thenPassRequestBodyAsParameter( self): self.request = Request('POST', PATH + "/dictionary", {}, "", BODY) response = self.resource_invocator.invoke(self.request) self.assertEqual(ResourceClass.the_response, response) def test_givenRouteWhichTakesADtoAsParameter_whenInvoking_thenDeserializeRequestBodyIntoTheDtoClass( self): self.request = Request('POST', PATH + "/dto", {}, "", DTO_BODY) response = self.resource_invocator.invoke(self.request) self.assertEqual(ResourceClass.the_response, response) def test_givenRouteWhichTakesADtoWithoutAnExplicitConstructor_whenInvoking_thenDeserializeRequestBodyIntoDto( self): self.request = Request('POST', PATH + "/dto-no-param", {}, "", DTO_BODY) response = self.resource_invocator.invoke(self.request) self.assertEqual(ResourceClass.the_response, response) def test_givenRouteWithPathParameters_whenInvoking_thenPassAsArguments( self): self.request = Request('GET', PATH + "/path-param/" + A_PATH_PARAM, {}, "", "") response = self.resource_invocator.invoke(self.request) self.assertEqual(A_PATH_PARAM, response.body) def test_givenRouteWithNumericPathParameter_whenInvoking_thenParseStringToNumberBeforePassing( self): a_numeric_path_param = 5 self.request = Request( 'GET', PATH + "/numeric-param/" + str(a_numeric_path_param), {}, "", "") response = self.resource_invocator.invoke(self.request) self.assertEqual(a_numeric_path_param, response.body) def test_givenRouteWithQueryParameter_whenInvoking_thenParseQueryParametersBeforeInvoking( self): name = "foobar" self.request = Request('GET', PATH + "/query-param", {}, "name=" + name, "") response = self.resource_invocator.invoke(self.request) self.assertEqual(name, response.body) def test_givenEscapedQueryParameter_whenInvoking_thenUnescapeBeforeInvoking( self): escaped_name = "rocket%20man" unescaped_name = "rocket man" self.request = Request('GET', PATH + "/query-param", {}, "name=" + escaped_name, "") response = self.resource_invocator.invoke(self.request) self.assertEqual(unescaped_name, response.body) def test_givenEscapedPathParameter_whenInvoking_thenUnescapeBeforeInvoking( self): escaped_name = "rocket%20man" unescaped_name = "rocket man" self.request = Request('GET', PATH + "/path-param/" + escaped_name, {}, "", "") response = self.resource_invocator.invoke(self.request) self.assertEqual(unescaped_name, response.body) def test_givenIncorrectParameters_whenInvoking_thenThrowIncorrectResourceParametersException( self): self.request = Request('POST', PATH + "/dto", {}, "", "") with self.assertRaises(IncorrectResourceParametersException): self.resource_invocator.invoke(self.request) def test_givenOverloadedRouteRegistrations_whenInvoking_thenChooseMethodBasedOnMethodSignature( self): self.request = Request('GET', PATH + "/overloaded", {}, "query=foo", "") response = self.resource_invocator.invoke(self.request) self.assertEqual(ResourceClass.OVERLOADED_RETURN, response.body) def test_givenMissingOptionalResourceArgument_whenInvoking_thenCallEvenIfTheArgumentIsMissing( self): self.request = RequestBuilder().path(PATH + "/nullable-query").build() response = self.resource_invocator.invoke(self.request) self.assertEqual(None, response.body) def test_givenPresentOptionalResourceArgument_whenInvoking_thenCallResourceWithParameter( self): self.request = RequestBuilder().path( PATH + "/nullable-query").query_string("query=foo").build() response = self.resource_invocator.invoke(self.request) self.assertEqual("foo", response.body) def test_givenApplicationException_whenInvokingResource_thenLetTheExceptionRise( self): self.request = RequestBuilder().path(PATH + "/error").build() with self.assertRaises(AnException): self.resource_invocator.invoke(self.request) def test_givenResourceWithHeadersParameter_whenInvokingResource_thenInvokeRoutingMethodWithHeadersObject( self): self.request = RequestBuilder().path(PATH + "/headers").headers({ "foo": "bar" }).build() response = self.resource_invocator.invoke(self.request) self.assertEqual([("foo", "bar")], Stream(response.body).toList()) def test_givenSerializationError_whenInvokingResource_thenRaiseException( self): self.resource_invocator.deserializer = mock.create_autospec( Deserializer) self.resource_invocator.deserializer.deserialize.side_effect = SerializationException( ) self.request = RequestBuilder().method("POST").path(PATH + "/dto").build() with self.assertRaises(IncorrectResourceParametersException): self.resource_invocator.invoke(self.request)
def bind(self, service_locator: ServiceLocator): service_locator.bind(MethodNotAllowedExceptionMapper, MethodNotAllowedExceptionMapper) service_locator.bind(UnknownPathExceptionMapper, UnknownPathExceptionMapper) service_locator.bind(IncorrectResourceParametersExceptionMapper, IncorrectResourceParametersExceptionMapper) service_locator.bind(NoMatchingCorsRuleExceptionMapper, NoMatchingCorsRuleExceptionMapper)
def __init__(self): self.serviceLocator = ServiceLocator() AbstractContext.INSTANCE = self self.serviceLocator.bind(ServiceLocator, self.serviceLocator)
def setUp(self): self.event_bus_initializer = ReflectiveEventBusInitializer(ServiceLocator(), Registry(), "")
def setUp(self): self.service_locator = ServiceLocator() self.dependency_mock = mock.MagicMock() self.service_locator.bind(object, self.dependency_mock) self.service_locator.bind(MessageDispatcherRunnableMock, MessageDispatcherRunnableMock)
def __init__(self): self.serviceLocator = ServiceLocator() self.INSTANCE = self self.serviceLocator.bind(ServiceLocator, self.serviceLocator)
def setUp(self): self.service_locator = ServiceLocator() self.registry = Registry() self.binder = AnnotatedClassBinder("", self.registry, _binding_annotation)
def setUp(self): self.route_handler_factory_mock = mock.create_autospec(RouteHandlerFactory) self.filter_chain_factory = FilterChainFactory([ FilteringRule("*", [DEFAULT_FILTER]), FilteringRule("/foo/bar*", [SPECIFIC_FILTER]) ], ServiceLocator(), self.route_handler_factory_mock)
def bind(self, service_locator: ServiceLocator): providers = self.registry.get_annotated_in_package( Provider, self.rootPackage) Stream(providers).map(lambda r: r.registered) \ .forEach(lambda p: service_locator.bind(_function_return_type(p), p))
def bind(self, service_locator: ServiceLocator): service_locator.bind(MediaLibrary, InMemoryMediaLibrary) service_locator.bind(CoverArtRepository, InMemoryCoverArtRepository)